Synchronising concurrent access to data in C#

 Aug 11, 2014

It’s fairly straightforward to start new threads in C# to run sections of code concurrently in a multi-core machine. Done properly, multithreading can dramatically improve the performance and responsiveness of your applications. One of the biggest challenges with multithreading is to synchronise access to shared data objects by all the concurrently running threads. In this article, I will explain one technique to synchronise concurrent access to data in C#.  One way to spin up new threads is illustrated in the following code snippet:
ThreadPool.RunAsync( async (s) => { await LoadUnsaved(); }, WorkItemPriority.Normal);
The asynchronous method LoadUnsaved in the above snippet could be a long running method that would block the main thread unnecessarily. By using the ThreadPool.RunAsync method, we will execute LoadUnsaved in its own thread without blocking the calling thread. We could have several calls to ThreadPool.RunAsync running whatever we want in separate threads concurrently without blocking the main thread where the UI is running. With this, the application remains responsive and the individual tasks running concurrently in those threads would finish quicker than running them one by one in sequence. If the threads do not share any resources then we are done, and there would be no need to worry about synchronisation issues. A problem arises if some of the threads access the same resource. For concreteness, let’s say that the resource is a collection of Customer objects and you need to synchronise access to the collection. There are a number of techniques to do that and here, I will illustrate the use of the ReaderWriterLockSlim class. First, you need to declare and instantiate the ReaderWriterLockSlim class with the below code:
private ReaderWriterLockSlim lockCustomers = new ReaderWriterLockSlim();
Now, if the code running in the thread needs to only read from the collection, you will use this:
lockCustomers.EnterReadLock(); //code reading from the collection… lockCustomers.ExitReadLock();
Many threads would be able to run the code, as above, concurrently. It’s safe to read from collections concurrently, but if we need to update the collection, say by adding new customers or deleting an existing one, we need to acquire a write lock with code like the following:
lockCustomers.EnterWriteLock(); //code modifying the collection… lockCustomers.ExitWriteLock();
In this case, the first thread calling EnterWriteLock will acquire the write lock, and all other threads will be blocked until it releases the lock by calling ExitWriteLock. Note, that the first thread to call EnterWriteLock will need to wait until an eventual read lock is released. We can have several threads using the same read lock, but just one thread will ever get the write lock. If you don’t take the care of synchronising access, the code would compile but the results are unpredictable. Synchronisation is one of the biggest challenges to overcome in multithreading programming. Today I have only illustrated one of the techniques for synchronisation. For more details, I recommend you take a look at the course 20483 - Programming in C# Using Visual Studio 2012.

How do your Excel skills stack up?   

Test Now  

About the Author:

Newton Godoy  

With over 17 years of in-class training experience and over 16 years of industry experience, Newton offers students a wealth of real-world technical knowledge and expertise in the areas of .NET application development, SQL Server and SharePoint Server. After spending several years lecturing as a professor, Newton found his true calling and began his career as a MCT. He worked as a technical trainer for some of Brazil's and Australia’s largest corporate training organisations before finally finding a home with New Horizons where he is now one of our top trainers. Newton brings a thorough mentoring capability to the classroom where he can advise on technical issues and challenges often beyond the scope of the course curriculum. His combination of technical knowledge and instructor experience make him one of the most respected instructors within the IT training industry.

Read full bio
Back to top