对于多线程的线程安全的最佳C#解决方案的读/写锁定?

对于多线程的线程安全的最佳C#解决方案的读/写锁定?

问题描述:

什么是最安全的(最短)的方式都锁定在多线程环境在C#中的读/写访问静态的成员?

What is the safest (and shortest) way do lock read/write access to static members in a multithreaded environment in C#?

是否有可能做线程锁定和放大器;在解锁类级别(所以我不不断重复锁定/解锁code每次静态成员的访问是必要的)?

Is it possible to do the threadsafe locking & unlocking on class level (so I don't keep repeating lock/unlock code every time static member access is needed)?

修改:样品code将是巨大的:)

Edit: Sample code would be great :)

修改:我应该使用挥发性关键字或 Thread.MemoryBarrier(),以避免多处理器缓存或者是不必要的?据乔恩斯基特只有那些将进行更改看到其他处理器? (问这个单独的here).

Edit: Should I use the volatile keyword or Thread.MemoryBarrier() to avoid multiprocessor caching or is that unnecessary? According to Jon Skeet only those will make changes visible to other processors? (Asked this separately here).

最安全,最短的方法是创建类型的私有,静态字段对象即只使用用于锁定(认为它是一个挂锁对象)。利用这一点,仅此字段来锁定,因为这prevent其他类型的锁定您的code时,然后在同一类型的,你做的锁。

The safest and shortest way is to create a private, static field of type Object that is only used for locking (think of it as a "pad-lock" object). Use this and only this field to lock on as this prevent other types from locking up your code when then lock on the same type that you do.

如果您在类型本身存在的风险,另一种类型也将决定你的类型的锁,这可能造成死锁。锁定

If you lock on the type itself there is risk that another type will also decide to lock on your type and this could create deadlocks.

下面是一个例子:

class Test
{
    static readonly Object fooLock = new Object();
    static String foo;

    public static String Foo
    {
    	get { return foo; }
    	set
    	{
    		lock (fooLock)
    		{
    			foo = value;
    		}
    	}
    }
}

请注意,我已经锁定创建一个私有的,静态字段 - 我使用该字段锁定写入操作的那场

Notice that I have create a private, static field for locking foo - I use that field to lock the write operations on that field.