正如著名的blog post from Stephen Cleary所规定的那样,永远不要尝试同步运行异步代码(例如,通过Task.RunSynchronously()
或访问Task.Result
)。另一方面,您不能在lock
语句中使用async/await。
我的用例是ASP.NET Core应用程序,它使用IMemoryCache
缓存一些数据。现在,当数据不可用时(例如删除缓存),我必须重新填充它,应该使用lock
保护它。
public TItem Get<TItem>(object key, Func<TItem> factory)
{
if (!_memoryCache.TryGetValue(key, out TItem value))
{
lock (_locker)
{
if (!_memoryCache.TryGetValue(key, out value))
{
value = factory();
Set(key, value);
}
}
}
return value;
}
在此示例中,工厂功能不能异步!如果必须异步该怎么办?
最佳答案
协调对共享变量的异步访问的一种简单方法是使用 SemaphoreSlim
。您调用WaitAsync
开始异步锁定,并调用Release
结束异步锁定。
例如。
private static readonly SemaphoreSlim _cachedCustomersAsyncLock = new SemaphoreSlim(1, 1);
private static ICollection<Customer> _cachedCustomers;
private async Task<ICollection<Customer>> GetCustomers()
{
if (_cachedCustomers is null)
{
await _cachedCustomersAsyncLock.WaitAsync();
try
{
if (_cachedCustomers is null)
{
_cachedCustomers = GetCustomersFromDatabase();
}
}
finally
{
_cachedCustomersAsyncLock.Release();
}
}
return _cachedCustomers;
}
关于c# - 如何将异步与锁定结合起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44269412/