聚会有点晚了,但是..
我也必须处理这个问题。并且所有解决方案都使用 Tasks 而不是 ValueTask 与 IDisposable 释放器结合使用。 (所以你总是要等待它)
如果不需要,我宁愿尝试在没有任何等待的情况下获得锁。所以我想出了一种不同的方法,将一个函数传递给它,该函数将在锁内执行。
返回 ValueTask 的 ReadersWriterLock Async。所以当锁被直接取走时,你不必等待它。
此库将按请求的顺序处理锁。它还支持在其启动的 SynchronizationContext 上继续。 (对 UI 线程有用)
我同意“尤其是异步代码的情况;在执行 I/O 时持有锁并不常见。”
问题是,您可以使用异步代码等待锁中的代码执行完毕,并在需要时等待它。这并不意味着锁中的代码必须是异步的。
这是一个例子:
class Program
{
static async Task Main(string[] args)
{
var rwl = new AsyncReadersWriterLock();
Console.WriteLine("* Example 1");
// run example 1
var result1 = Example1(rwl);
if (!result1.IsCompleted)
await result1;
Console.WriteLine("");
Console.WriteLine("* Example 2");
// run example 2
var result2 = Example2(rwl);
if (!result2.IsCompleted)
await result2;
}
private static async ValueTask Example1(AsyncReadersWriterLock rwl)
{
Console.WriteLine("Before calling UseReaderAsync");
var result = rwl.UseReaderAsync(async () =>
{
Console.WriteLine("Reader start");
await Task.Delay(1000);
Console.WriteLine("Reader end");
});
Console.WriteLine("After calling UseReaderAsync");
Console.WriteLine("");
if (!result.IsCompleted)
{
Console.WriteLine("result.IsCompleted == false, awaiting");
await result;
Console.WriteLine("await finished");
}
else
Console.WriteLine("result.IsCompleted == true, no await is used");
}
private static async ValueTask Example2(AsyncReadersWriterLock rwl)
{
Console.WriteLine("Before calling UseReaderAsync");
var result = rwl.UseReaderAsync(() =>
{
Console.WriteLine("Reader start");
// no async is used
//await Task.Delay(1000);
Console.WriteLine("Reader end");
});
Console.WriteLine("After calling UseReaderAsync");
Console.WriteLine("");
if (!result.IsCompleted)
{
Console.WriteLine("result.IsCompleted == false, awaiting");
await result;
Console.WriteLine("await finished");
}
else
Console.WriteLine("result.IsCompleted == true, no await is used");
}
}
导致:
* Example 1
Before calling UseReaderAsync
Reader start
After calling UseReaderAsync
result.IsCompleted == false, awaiting
Reader end
await finished
* Example 2
Before calling UseReaderAsync
Reader start
Reader end
After calling UseReaderAsync
result.IsCompleted == true
我还在努力。 (我对 github/创建 nuget 包没有太多经验,所以欢迎提出任何想法)
包裹:nuget
来源:github