且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在队列或等待列表C#异步任务

更新时间:2021-08-03 01:31:19

其实,任务的启动的,只要你拨打的DoWork ;当你等待它们,你的整理的任务。

Actually, the tasks start as soon as you call DoWork; when you await them, you are finishing the tasks.

节流任务的一个选择是SemaphoreSlim$c$c>,你可以这样使用:

One option for throttling tasks is SemaphoreSlim, which you can use as such:

private SemaphoreSlim _mutex = new SemaphoreSlim(3);
public async Task DoWorkAsync()
{
  await _mutex.WaitAsync();
  try
  {
    ...
  }
  finally
  {
    _mutex.Release();
  }
}

另一种选择是使用一个实际的队列,像ActionBlock<T>$c$c>,它有内置的限制支持。

Another option is to use an actual queue, like an ActionBlock<T>, which has built-in throttling support.