Lock a single variable in multi threaded applications
This article represents about lock a single variable in multi threaded applications with code snippet
Instead of locking the entire object using the lock() statement in C#, the following code uses the InterLocked Class to perform thread-safe write operation on a variable. Because the following example uses the shared variable, the new value for the variable is available in both the threads.
static int x = 100;
static void Main(string[] args)
{
Thread t1 = new Thread(delegate() { UpdateValue(); });
t1.Start();
Thread t2 = new Thread(delegate() { UpdateValue(); });
t2.Start();
}
static void UpdateValue()
{
Console.WriteLine("Output:");
// Value of x is set to 30 here
if (Interlocked.Exchange(ref Sample.x, 30) == 0)
{
Console.WriteLine("{0} static value is {1}", Thread.CurrentThread.Name, x);
// Variable x is released after setting the value
Interlocked.Exchange(ref Sample.x, 0);
}
else
{
Console.WriteLine("{0} is denied access to the static value x", Thread.CurrentThread.Name);
}
}

Apparently this is what the esteemed Willis was talking about.