I was reading about threading and about locking. It is common practise that you can't (well should not) lock a value type.
So the question is, what is the recommended way of locking a value type? I know there's a few ways to go about doing one thing but I haven't seen an example. Although there was a good thread on MSDN forums but I can't seem to find that now.
Thanks
The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.
Avoid using 'lock keyword' on string object String object: Avoid using lock statements on string objects, because the interned strings are essentially global in nature and may be blocked by other threads without your knowledge, which can cause a deadlock.
According to Microsoft: The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
C# doesn't allow locking on a null value.
Use another object for the lock.
int valueType;
object valueTypeLock = new object();
void Foo()
{
lock (valueTypeLock)
{
valueType = 0;
}
}
Your question is worded in such a way that it suggests to me that you don't entirely understand locking. You don't lock the data, you lock to protect the integrity of the data. The object you lock on is inconsequential. What matters is that you lock on the same object in other areas of your code that alter the data being protected.
Depend on your situation you might be able to avoid using locks by leveraging System.Threading.Interlocked the same code in Jon's example becomes:
System.Threading.Interlocked.Exchange(valueType,0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With