I am working on a multi threaded WindowsPhone8 app that has critical sections within async methods.
Does anyone know of a way to properly use semaphores / mutexes in C
First, read through Stephen Cleary's blog post, which he linked to in his answer. He mentions multiple reasons, such as uncertain lock state and inconsistent invariants, which are associated with recursive locks (not to mention recursive async locks). If you can do the refactoring he and Knickedi describe in their answers, that would be great.
However, there are some cases where that type of refactoring is just not possible. Fortunately, there are now multiple libraries which support nested async calls (lock reentrance). Here are two. The author of the first has a blog post where he talks more about it.
You can incorporate it into your code as such (using the first library in this example):
public class Foo
{
AsyncLock _lock = new AsyncLock();
public async Task Bar()
{
// This first LockAsync() call should not block
using (await _lock.LockAsync())
{
await BarInternal();
}
}
public async Task BarInternal()
{
// This second call to LockAsync() will be recognized
// as being a reëntrant call and go through
using (await _lock.LockAsync()) // no deadlock
{
// do work
}
}
}