I would like to
Monitor.Enter(this.StaticLock);
try
{
// Do something ...
ThreadPool.QueueUserWorkItem(state =>
{
try
{
// Do something else...
}
finally
{
Monitor.Exit(this.StaticLock);
}
});
}
catch (Exception)
{
Monitor.Exit(this.StaticLock);
throw;
}
But it doesn't work since the it can't Monitor.Exit on an object that wasn't Monitor.Enter in the current thread. How to do that? Should I use interthread communication?
How to transfer locks between threads?
You enter the monitor on the initial thread, say thread Alpha. Any other threads that try to enter the monitor will block until the monitor is available.
If you then want to transfer the lock to another thread, say thread Bravo, while still being able to resume thread Alpha with ownership of the monitor when Bravo is done, then you put Alpha in a wait state on the monitor. If thread Bravo is blocked on the monitor then it wakes up and enters the monitor. When it is done it pulses the monitor, which abandons Bravo's ownership of the monitor and transfers ownership back to Alpha, which wakes up and keeps on running with its ownership of the monitor.
If that is totally not clear to you then (1) you shouldn't be trying to do this in the first place; this is super dangerous if you get it wrong, and (2) you should read this:
http://www.codeproject.com/Articles/28785/Thread-synchronization-Wait-and-Pulse-demystified
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With