C# async tasks in a queue or waiting list

后端 未结 1 1733
轮回少年
轮回少年 2021-02-03 13:33

i have an async Task like this:

public async Task DoWork()
{

}

And i have at the moment a:

List tmp = new List<         


        
相关标签:
1条回答
  • 2021-02-03 14:05

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

    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();
      }
    }
    

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

    0 讨论(0)
提交回复
热议问题