.Net6 AsyncEx 异步锁 电脑版发表于:2022/7/1 16:28 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.Net6 AsyncEx [TOC] tn2>简单来讲就是可以通过异步方式实现锁。 安装 ------------ ```bash <PackageReference Include="Nito.AsyncEx" Version="5.1.2" /> ``` 测试代码 ------------ tn2>可以通过`LockAsync`,`Lock`方法实现锁,当我们自定义锁的Token时,在锁中执行时常超过了Token时限将会自动抛出`OperationCanceledException`异常。 ```csharp [TestClass] public class TestAsyncEx { [TestMethod] public async void TestUseLockAsync() { await UseLockAsync(); } private readonly AsyncLock _mutex = new AsyncLock(); public async Task UseLockAsync() { // AsyncLock可以异步锁定 using (await _mutex.LockAsync()) { // 锁在那里等待是安全的 await Task.Delay(TimeSpan.FromSeconds(1)); } } [TestMethod] public async Task TestUseLockAsyncToken() { try { await UseLockAsyncToken(); } catch (OperationCanceledException ex) { throw; } } public async Task UseLockAsyncToken() { // 仅尝试锁定2秒钟。 var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2)); // 如果2秒后锁不可用,这将引发OperationCanceledException。 using (await _mutex.LockAsync(cts.Token)) { await Task.Delay(TimeSpan.FromSeconds(10), cts.Token); } } [TestMethod] public void TestUseLock() { UseLock(); } public void UseLock() { using (_mutex.Lock()) { Thread.Sleep(TimeSpan.FromSeconds(1)); } } } ```