Cannot do await inside lock

In .NET, you cannot do lock and then await some task inside the inner block. In order to handle it correctly, you have to create a static semaphore instance and simulate locking with it, here is an example:


private static readonly SemaphoreSlim _syncLock = new (1, 1);

private void SomeMethod() 
{
	await _syncLock.WaitAsync();

	try 
    {
    	await SomeTask();
    }
    finally
    {
    	_syncLock.Release();
    }

}

Post a Comment

Previous Post Next Post