Alex Alex - 4 months ago 39
C# Question

Best C# solution for multithreaded threadsafe read/write locking?

What is the safest (and shortest) way do lock read/write access to

members in a multithreaded environment in C#?

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)?

Edit: Sample code would be great :)

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).


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.

Here is an example:

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

    public static String Foo
    	get { return foo; }
    		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.