What is the safest (and shortest) way do lock read/write access to static
members in a multithreaded environment in C#?
Is it possible to do the thread
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; }
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.