【问题标题】:Lock the method until it completes the execution [duplicate]锁定方法直到它完成执行[重复]
【发布时间】:2020-11-21 08:38:48
【问题描述】:

我有一个进程每两分钟运行一次并执行该方法。

有时,该过程需要两分钟以上。在这种情况下,我希望进程等到进程完成。

我的代码如下所示。我尝试了锁定,监视器,但由于异步等待而没有工作。我收到此错误 SynchronizationLockException on Monitor.Exit when using await

public async Task RunProcess()
{
   await GetRecords();
   await CheckDuplicates();
   await InsertRecords();
}

实现这一点的最佳做法是什么?

【问题讨论】:

  • 确保你调用的方法也是异步的
  • 还有this answer
  • 如果这个进程每隔几分钟运行一次,为什么还要使用异步呢?完全同步 abd 然后锁定将起作用。如果此进程是 en exe,则使用监视器将无济于事,因为它的范围是整个进程
  • @BrootsWaymb 我完全不明白这个答案
  • @Chatra - 哪一部分?您是否查看了最佳答案提到的 SemaphoreSlim 类?

标签: c# multithreading locking


【解决方案1】:

SemaphoreSlim 是异步兼容的互斥原语(即“锁定”):

private SemaphoreSlim _processLock = new SemaphoreSlim(1);
public async Task RunProcess()
{
  await _processLock.WaitAsync();
  try
  {
    await GetRecords();
    await CheckDuplicates();
    await InsertRecords();
  }
  finally
  {
    _processLock.Release();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多