c# – MSpec:如何使静态变量线程安全?

我正在使用MSpec作为我的最新项目,总的来说我对它非常满意.但是,当我的测试以并行方式运行时,我确实遇到并发问题,我想知道是否有人遇到过这个问题,或者更好的是,有一个解决方案?

MSpec严重依赖静态方法和变量来工作.

现在,当我在我的基类中定义静态变量时,它会被多个测试类使用,并且我在paralel中运行我的测试,它们共享相同的静态变量,从而干扰彼此.

我正在使用NCrunch和Resharper作为我的测试人员,我遇到了这两个问题.

有人熟悉这个问题吗?

解决方法

首先,我建议阅读 Thead Safety Guidelines on MSDN.这将使您很好地了解如何以及为什么在C#中使方法线程安全.

The following rules outline the design guidelines for implementing threading:

  • Avoid providing static methods that alter static state. In common server scenarios,static state is shared across requests,which means multiple threads can execute that code at the same time. This opens up the possibility for threading bugs. Consider using a design pattern that encapsulates data into instances that are not shared across requests.
  • … Adding locks to create thread-safe code decreases performance,increases lock contention,and creates the possibility for deadlock bugs to occur
  • Be aware of method calls in locked sections. Deadlocks can result when a static method in class A calls static methods in class B and vice versa. If A and B both synchronize their static methods,this will cause a deadlock. You might discover this deadlock only under heavy threading stress.
  • Be aware of issues with the lock statement (SyncLock in Visual Basic). It is tempting to use the lock statement to solve all threading problems. However,the System.Threading.Interlocked Class is superior for updates that must be atomic …

作为一般说明,我更喜欢使用的方法(如果可能)是制作方法(静态或其他方式)immutable.为此,所有变量应该是本地的(在堆栈本地创建,或作为参数传递给a方法).通过确保仅使用局部变量,或者成员变量是不可变的,每个线程将在其自己的隔离区中操作,对变量的更改不会影响另一个线程.这是我在.NET仿真软件中广泛使用的一种方法,允许在C#中实现无锁且因此高性能的多线程.

或者,如果变量必须是成员变量,则可以通过锁定关键字保护对它们的可变访问.小心使用lock会导致上下文切换(减速)并引入死锁情况的可能性.它也不保证线程安全,因为使用锁必须防止您试图阻止的特定方案.

为了进一步阅读,我建议查看这些描述C#中线程安全性和不变性的相关问题:

> Designing a Thread Safe class
> Achieving Thread Safety
> Why are immutable objects thread safe

最好的祝福,

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...