Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly lock a value type?

Tags:

c#

locking

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

like image 742
GurdeepS Avatar asked Jan 07 '09 15:01

GurdeepS


People also ask

How do you lock a method in C#?

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.

Why should you avoid the lock keyword?

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.

What is lock keyword?

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.

Can you lock a null object C#?

C# doesn't allow locking on a null value.


3 Answers

Use another object for the lock.

int valueType;
object valueTypeLock = new object();

void Foo()
{
    lock (valueTypeLock)
    {
        valueType = 0;
    }
}
like image 163
Jon B Avatar answered Oct 12 '22 14:10

Jon B


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.

like image 28
Kent Boogaart Avatar answered Oct 12 '22 13:10

Kent Boogaart


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)
like image 32
JoshBerke Avatar answered Oct 12 '22 13:10

JoshBerke