AsyncLock to configure multiple methods

I need to achieve:

  • When MasterAsync is running, HumbleSlave1Async and HumbleSlave2Async CANNOT.
  • Vice Versa- When one or both of the slaves are executed, MasterAsync CANNOT.
  • The hard part - subordinates cannot block each other.

(link to used AsyncLock ).

    private async Task MasterAsync()
    {
        using (await _asyncLock.LockAsync())
        {
            await Task.Delay(2000);
        }
    }
    private async Task HumbleSlave1Async()
    {
        using (await _asyncLock.LockAsync())
        {
            await Task.Delay(5000);
        }
    }
    private async Task HumbleSlave2Async()
    {
        using (await _asyncLock.LockAsync())
        {
            await Task.Delay(5000);
        }
    }

I'm not sure how to solve it, I thought about using two different locks for each subordinate in MasterAsync, but then one lock would be in the other:

    private async Task MasterAsync()
    {
        using (await _asyncLock1.LockAsync())
        {
            using (await _asyncLock2.LockAsync())
            {
                await Task.Delay(2000);
            }
        }
    }
    private async Task HumbleSlave1Async()
    {
        using (await _asyncLock1.LockAsync())
        {
            await Task.Delay(5000);
        }
    }
    private async Task HumbleSlave2Async()
    {
        using (await _asyncLock2.LockAsync())
        {
            await Task.Delay(5000);
        }
    }

Does this make sense and is it safe (dead ends, etc.), especially when I used AsyncLock?

+4
source share
3 answers

MasterAsync , HumbleSlave1Async HumbleSlave2Async . Vice Versa- , MasterAsync . - .

, . (, , ).

, /. RWL - , , "" ( - ) "" ( , ). async - , AsyncEx.

: :

private readonly AsyncReaderWriterLock _lock = new AsyncReaderWriterLock();
private async Task MasterAsync()
{
    using (await _lock.WriterLockAsync())
    {
        await Task.Delay(2000);
    }
}
private async Task HumbleSlave1Async()
{
    using (await _lock.ReaderLockAsync())
    {
        await Task.Delay(5000);
    }
}
private async Task HumbleSlave2Async()
{
    using (await _lock.ReaderLockAsync())
    {
        await Task.Delay(5000);
    }
}
+5

, HumbleSlave2Async MasterAsync, asyncLock1 asyncLock2, HumbleSlave1Async ( asyncLock1 MasterAsync). , № 3 .

, - AsyncManualResetEvent, .

+1

This, of course, will not be inhibited, because you acquire locks always in the same order:

  • _asyncLock1(or you did not purchase it for HumbleSlave2Async)
  • _asyncLock2(or you did not purchase it for HumbleSlave1Async)

The general locking procedure guarantees freedom of deadlocks.

+1
source

All Articles