【问题标题】:C# How To Achieve Monitor.Enter/Exit With Task Based AsyncC#如何使用基于任务的异步实现Monitor.Enter/Exit
【发布时间】:2018-12-17 00:14:16
【问题描述】:

这是我的有效代码。如果它不是基于任务的异步,我就不必这样做,但是使用 Monitor.Enter/Exit 会导致这个问题Object synchronization method was called from an unsynchronized block of code. Exception on Mutex.Release()

人们提到过使用 AutoResetEvent 和 SemaphoreSlim,但我不太确定哪种模式适合。

private bool fakelock;

internal async Task<byte[][]> ExchangeCore(byte[][] apdus)
{
    if (apdus == null || apdus.Length == 0)
        return null;
    List<byte[]> resultList = new List<byte[]>();
    var lastAPDU = apdus.Last();

    while (fakelock)
    {
        await Task.Delay(100);
    }

    fakelock = true;

    foreach (var apdu in apdus)
    {
        await WriteAsync(apdu);
        var result = await ReadAsync();
        resultList.Add(result);
    }

    fakelock = false;

    return resultList.ToArray();
}

【问题讨论】:

    标签: c# multithreading asynchronous locking


    【解决方案1】:

    您也许可以使用支持异步的 SemaphoreSlim。

    private static SemaphoreSlim Semaphore = new SemaphoreSlim(1, 1);
    
    internal async Task<byte[][]> ExchangeCore(byte[][] apdus)
    {
        if (apdus == null || apdus.Length == 0)
            return null;
    
        await Semaphore.WaitAsync();
    
        try
        {
            List<byte[]> resultList = new List<byte[]>();
            foreach (var apdu in apdus)
            {
                await WriteAsync(apdu);
                var result = await ReadAsync();
                resultList.Add(result);
            }
            return resultList.ToArray();
        }
        finally
        {
            Semaphore.Release();
        }
    }
    

    【讨论】:

    猜你喜欢
    • 2013-01-05
    • 1970-01-01
    • 2017-04-22
    • 2013-09-09
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    相关资源
    最近更新 更多