繁体   English   中英

在异步库方法中处理共享成员变量的推荐做法是什么?

[英]What is recommended practice for handling shared member variables in an async library method?

在阅读了几篇关于 async await 的文章后,我现在明白了以下内容:

  • 作为库作者,您应该始终使用.ConfigureAwait(false)以避免对应用程序正在使用的SynchronizationContext做出假设
  • ConfigureAwait(false)的作用是它会使用线程池上下文,也就是说该方法的rest可以在任意空闲线程中运行
  • 您不能在lock块的主体中使用 await

Let's assume that you are creating a library that has async API methods on a non-static class, and that class has some member variables that are shared across its API methods. 您如何编写这些方法以确保以线程安全的方式访问成员变量?

根据您的需要,您可以使用其他BCL 同步原语控制async方法中的并发性

其中最简单的可能是SemaphoreSlim

Semaphore 和 SemaphoreSlim 类

System.Threading.SemaphoreSystem.Threading.SemaphoreSlim类限制了可以同时访问共享资源或资源池的线程数。 请求资源的其他线程等待直到任何线程释放信号量。 因为信号量没有线程亲和性,所以一个线程可以获取该信号量,另一个线程可以释放它。 SemaphoreSlim 是 Semaphore 的轻量级替代方案,只能用于单个进程边界内的同步。

例子

private SemaphoreSlim _sync = new SemaphoreSlim(1,1);

...

public async Task SomeMethodThatAccessSharedResources()
{
   await _sync.WaitAsync();
   try
   {
      // example of async call
      await Task.Delay(1000);
   }
   finally
   {

      _sync.Release();
   }
}

Michael Randall所展示的更多的是一种控制对代码某些部分的访问的方法。

同步原语所述, 互锁 class可用于更改单个类型成员字段。 根据文档

System.Threading.Interlocked class 提供了对变量执行简单原子操作的 static 方法。 这些原子操作包括加法、递增和递减、交换和依赖于比较的条件交换,以及 64 位 integer 值的读取操作。

有关详细信息,请参阅联锁 API参考。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM