Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread Synchronization in .NET

In my app I have a List of objects. I'm going to have a process (thread) running every few minutes that will update the values in this list. I'll have other processes (other threads) that will just read this data, and they may attempt to do so at the same time.

When the list is being updated, I don't want any other process to be able to read the data. However, I don't want the read-only processes to block each other when no updating is occurring. Finally, if a process is reading the data, the process that updates the data must wait until the process reading the data is finished.

What sort of locking should I implement to achieve this?

like image 635
Randy Minder Avatar asked Jan 26 '26 05:01

Randy Minder


1 Answers

This is what you are looking for.

ReaderWriterLockSlim is a class that will handle scenario that you have asked for. You have 2 pair of functions at your disposal:

  • EnterWriteLock and ExitWriteLock
  • EnterReadLock and ExitReadLock

The first one will wait, till all other locks are off, both read and write, so it will give you access like lock() would do.

The second one is compatible with each other, you can have multiple read locks at any given time.

Because there's no syntactic sugar like with lock() statement, make sure you will never forget to Exit lock, because of Exception or anything else. So use it in form like this:

try
{
lock.EnterWriteLock(); //ReadLock

//Your code here, which can possibly throw an exception.

}
finally
{
lock.ExitWriteLock(); //ReadLock
}
like image 192
Marcin Deptuła Avatar answered Jan 28 '26 18:01

Marcin Deptuła