Async + sync completion + lock

Let’s suppose that you have 2 functions = one true sync and one true async . Let’s suppose more that the sync one can must finish before calling next time ( think about some weird COM component or , in our days, SqlConnection )

If we look just at the async function , we could wait for all. However, the sync function must be called sync

One solution is to make different calls:


var list = new List<Task<int>>(nr);
//add async to list

await Task.WhenAll(list)

//call each sync



But I want to make really async – and one solution is lock

We could wrote the sync function in async manner like this:


//SemaphoreSlim sem = new SemaphoreSlim(1);
static object myObject = new object();
async Task<int> syncTask(int i)         {             
lock (myObject)             
//try{                 
//await sem.WaitAsync();                                 
CallSyncFunction();                             
//}             
//finally             
//{                 
//sem.Release();             
//}                                   
}

The trick that I  used is lock, because the syntax is easier than SemaphoreSlim (BTW: if you want to learn about threading, jump directly to http://www.albahari.com/threading/)
In this manner, the sync function is modified in async -and, more, it waits for completion before entering the second time.

The code is on github on

More details in the Wiki https://github.com/ignatandrei/AsyncSyncLock/wiki or in the code https://github.com/ignatandrei/AsyncSyncLock/