Share data between Tasks using locks in .NET C# in separate regions
February 7, 2014 Leave a comment
In the this post we saw how to use the ‘lock’ keyword to restrict access to a single critical region. You can reuse the same lock object to synchronise access to the shared variable in separate regions. The modified version of the code in the referenced post looks as follows with two critical regions:
BankAccount account = new BankAccount(); List<Task> incrementTasks = new List<Task>(); List<Task> decrementTasks = new List<Task>(); object lockObject = new object(); for (int i = 0; i < 5; i++) { incrementTasks.Add(Task.Factory.StartNew(() => { for (int j = 0; j < 1000; j++) { lock (lockObject) { account.Balance++; } } })); } for (int i = 0; i < 5; i++) { decrementTasks.Add(Task.Factory.StartNew(() => { for (int j = 0; j < 1000; j++) { lock (lockObject) { account.Balance--; } } })); } Task.WaitAll(incrementTasks.ToArray()); Task.WaitAll(decrementTasks.ToArray()); Console.WriteLine(string.Concat( "Expected value: 0, actual value: ", account.Balance));
We have two sets of tasks: one that increases the balance and another that reduces it. By reusing the same lock object in both cases we can ensure that it’s always at most one task that has access to the shared variable.
View the list of posts on the Task Parallel Library here.