In my application I use a ReaderWriterLockSlim
to synchronize reads and writes from/to a list<>
.
In the following example reading the list is performed inside all 3 sub-methods, thus these 3 should be packed into a ReadLock
. The problem is that SubMethod3
is called via a BackgroundWorker
(as it contains lengthy calculations), so the ExitReadLock()
in the finally block of MainMethod1 might be called before SubMethod3 has been finished by the BackgroundWorker
(separate thread). Thereby the code in SubMethod3
is not really protected by the lock.
What I have considered is to use a lock in each sub-method, so Submethod3
would have its own lock, which would be released when the BackgroundWorker
was done. The problem with this approach is that another thread could enter in between the calls of the sub-methods, as each of these would release the lock when done.
My question is: How can ReadLock
be used to protect over more threads?
ReaderWriterLockSlim synchronizationLock = new ReaderWriterLockSlim();
public void MainMethod1()
{
synchronizationLock.EnterReadLock();
try
{
SubMethod1(); //Run on UI thread
SubMethod2(); //Run on UI thread
myBackgroundWorker.RunWorkerAsync();
}
finally
{
synchronizationLock.ExitReadLock();
}
}
private void myBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
SubMethod3(); //Run on separate thread
}