0

I have one little task - i have to create mutex,using tasks and async\await,that not blocking current thread(UI thread).

Mutex interface:

Lock() – returns a Task, wich will be completed only when mutex will become free. This task must be unique per lock to disallow more than 1 unblock per Release() call. Release() – release mutex. One and only one of tasks, returned by Lock(), must become completed. That mutex have to work in a such way

await mutex.Lock();
// critical code  
mutex.Release();

I wrote some piece of code(see link in the end),but if briefly describe the problem is: I create a class Mutex. In the method Lock i do something like that:

await Task.Factory.StartNew(() =>
{
    mutex.WaitOne();
    UserDispatcher = Dispatcher.CurrentDispatcher;
});

In the method Release i do something like that:

if (mutex != null && UserDispatcher != null)
{
    UserDispatcher.Invoke(new Action(() =>
    {
        Console.WriteLine("Releasing");
        mutex.ReleaseMutex();
    }));
}

When i`m trying release mutex,my program just freeze forever. What the problem?

Full code: https://www.dropbox.com/s/4a370cn1bd2o0nz/MainWindow.xaml.cs?dl=0

Link to project: https://www.dropbox.com/sh/qsgle79jdgpr7cd/AAA3MZ6VlTNbUj-isgaQaLE-a?dl=0

progerz
  • 27
  • 1
  • 9

1 Answers1

0

You probably have a deadlock on your hands when the UI thread is stuck waiting for the mutex to be released on mutex.WaitOne(); and you're trying to release it using the same UI thread (which is blocked) by posting the mutex.ReleaseMutex(); on it using the dispatcher.

If you want an async mutex you can simply use a SemaphoreSlim set to 1 (hence, mutual exclusion) and call WaitAsync to wait asynchronously.

Here's my implementation of an AsyncLock (which is the same as an async mutex) using SemaphoreSlim.

Community
  • 1
  • 1
i3arnon
  • 113,022
  • 33
  • 324
  • 344
  • A little problem here... My Mutex have to work in a such way `await mutex.Lock();` , i can`t do that with semaphore( – progerz Dec 08 '14 at 16:36
  • @progerz you can with `SemaphoreSlim` and `WaitAsync`. – i3arnon Dec 08 '14 at 16:37
  • @i3aron and it will be work in a such way? Have you Skype or another messenger? I have few liitle questions about that. – progerz Dec 08 '14 at 16:49
  • @progerz It will. You have a full example in this question: http://stackoverflow.com/a/21011273/885318. It's better if you ask there if you have issues since it will be visible to everybody. – i3arnon Dec 08 '14 at 16:52