Sample code:
class Program
{
static readonly object locker = new object();
static void Main(string[] args)
{
Func();
Func();
Thread.Sleep(6000);
}
static void Func()
{
Monitor.Enter(locker);
Action act = () =>
{
Thread.Sleep(2000);
};
act.BeginInvoke(a =>
{
Console.WriteLine("exiting..");
Monitor.Exit(locker);
}, null);
Console.WriteLine("Func done...");
}
}
Ideally the console would print out:
Func done...
exiting...
Func done...
exitting...
But, I’m getting:
Func done...
Func done...
exitting...
and then Monitor.Exit throws the exception
Object synchronization method was called from an unsynchronized block of code.
What is the error here? What’s the preferred way to achieve this?
Monitor.Enter(locker) is on the current thread, Monitor.Exit is on a different thread as it is invoked from your current thread.
Thus you need to use Monitor.Wait and Monitor.Pulse as well, but ManualResetEvents are easier in your case.