【问题标题】:How to create an async method that can only execute from one thread at a time?如何创建一次只能从一个线程执行的异步方法?
【发布时间】:2018-05-09 03:36:04
【问题描述】:

我有一个 IO.Stream,我需要先写入然后再从中读取。由于响应直接与发送的数据相关联,因此我需要防止此方法并行执行,以保证其完整性。现在,我也希望这种方法可以等待,这可能吗?我将流包装成一个同步的流,这样可以防止读写过程中的干扰,但不能保证保持正确的读写操作顺序。我对如何实现这一点有点迷茫,因为如果我想使用异步等待方法,我无法锁定流。

【问题讨论】:

  • TPL DataFlow 听起来可能适合你
  • 仅供参考:您不应该担心哪些线程同时调用相同的方法:您应该担心哪些线程访问相同的数据。可能有不同的线程执行不同的方法,但仍然存在问题,因为两种方法都访问相同的数据。其他时候,你可以在同一个方法中同时有不同的线程,但不会有问题,因为它们是使用该方法对不同的数据进行操作。

标签: c# multithreading asynchronous locking


【解决方案1】:

您可以使用SemaphoreSlim.WaitAsync

    static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1,1);
    //Asynchronously wait to enter the Semaphore. If no-one has been granted access to the Semaphore, code execution will proceed, otherwise this thread waits here until the semaphore is released
    await semaphoreSlim.WaitAsync();
    try
    {
        await Task.Delay(1000);
    }
    finally
    {
        semaphoreSlim.Release();
    }

【讨论】:

    【解决方案2】:

    感谢您的回答,我找到了不同的解决方案。我正在排队发送命令并将它们与现在在单独线程中读取的响应相匹配。由于写入和读取是串行的,因此可以按顺序安全匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-08
      • 2014-03-04
      • 1970-01-01
      • 2020-10-22
      • 2020-09-23
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      相关资源
      最近更新 更多