【发布时间】: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