Mutex. If you are a developer than you heard about mutex. Mutex are used to ensure that only one thread/process has an exclusive access to a specific sections of the code.
Let’s look over the following code and see if the code is correct or not?
The above code release the mutex lock on an event handler that is executed on a different thread. The problem is that we don’t call the release mutex method from the same thread from where we call “WaitOne”. Because of this, the obtained behavior is not the one that we expect.
The same problem will appear if we use mutex in combination with delegates, lambda expression, Action/Func.
Let’s look over the following code and see if the code is correct or not?
public class Foo
{
Mutex mutex = new Mutex();
event SomeActionEvent someActionEvent;
public void Do()
{
mutex.WaitOne();
...
someActionEvent += OnSomeAction();
}
public void OnSomeAction(...)
{
mutex.ReleaseMutex();
}
}
“WaitOne” method is used to block the current thread until we received a release signal – WaitHandler. “ReleaseMutex” is used when we want to release the lock.The above code release the mutex lock on an event handler that is executed on a different thread. The problem is that we don’t call the release mutex method from the same thread from where we call “WaitOne”. Because of this, the obtained behavior is not the one that we expect.
The same problem will appear if we use mutex in combination with delegates, lambda expression, Action/Func.
public class Foo
{
Mutex mutex = new Mutex();
public void Do()
{
mutex.WaitOne();
...
MyMethod(()=>
{
mutex.ReleaseMutex();
});
}
}
This is not all. We will find this problem when we are using Task. This is happening because each task is/can be executed on a differed thread.public class Foo
{
Mutex mutex = new Mutex();
public void Do()
{
mutex.WaitOne();
...
Task.Factory.StartNew(()=>
{
...
mutex.ReleaseMutex();
});
}
}
There are different solutions for this problem from mutex with name to other ways of synchronization. What we should remember about anonymous mutex is that we need to call the release function from the same thread that made the lock.
Comments
Post a Comment