Share data between Tasks using locks in .NET C# in separate regions

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.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: