我的应用程序正在使用 .NET 4。我正在使用等待异步努吉特包 https://www.nuget.org/packages/Microsoft.Bcl.Async/
在我的应用程序中,我想对信号量 WaitAsync 调用进行等待,如下所示。
SemaphoreSlim semphore = new SemaphoreSlim(100);
await semphore.WaitAsync();
但是我收到以下编译错误。
“System.Threading.SemaphoreSlim”不包含“WaitAsync”的定义,并且找不到接受“System.Threading.SemaphoreSlim”类型的第一个参数的扩展方法“WaitAsync”(您是否缺少 using 指令或程序集引用?)
.NET 4.0 中是否可以使用 AWait Async?
你不能使用SemaphoreSlim.WaitAsync
在 .Net 4.0 中,因为此方法被添加到SemaphoreSlim http://msdn.microsoft.com/en-us/library/system.threading.semaphoreslim(v=vs.100).aspx在.Net 4.5中。
但是,您可以实现自己的AsyncSemaphore
遵循 Stephen Toub 的例子构建异步协调原语,第 5 部分:AsyncSemaphore https://devblogs.microsoft.com/pfxteam/building-async-coordination-primitives-part-5-asyncsemaphore/:
public class AsyncSemaphore
{
private readonly static Task s_completed = Task.FromResult(true);
private readonly Queue<TaskCompletionSource<bool>> m_waiters = new Queue<TaskCompletionSource<bool>>();
private int m_currentCount;
public AsyncSemaphore(int initialCount)
{
if (initialCount < 0) throw new ArgumentOutOfRangeException("initialCount");
m_currentCount = initialCount;
}
public Task WaitAsync()
{
lock (m_waiters)
{
if (m_currentCount > 0)
{
--m_currentCount;
return s_completed;
}
else
{
var waiter = new TaskCompletionSource<bool>();
m_waiters.Enqueue(waiter);
return waiter.Task;
}
}
}
public void Release()
{
TaskCompletionSource<bool> toRelease = null;
lock (m_waiters)
{
if (m_waiters.Count > 0)
toRelease = m_waiters.Dequeue();
else
++m_currentCount;
}
if (toRelease != null)
toRelease.SetResult(true);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)