C# async tasks in a queue or waiting list

放肆的年华 提交于 2019-12-18 11:33:48

问题


i have an async Task like this:

public async Task DoWork()
{

}

And i have at the moment a:

List<Task> tmp = new List<Task>();

where i add the tasks.

I start the tasks like this:

foreach (Task t in tmp)
{
    await t;
}

Now my Question:

What`s the best way to start the tasks and only run 3 of them, at the same time (until the others are waiting)?

I think i need something like a queue/waiting list?

It should also be possible to add more tasks after the queue is started.

I`am using .NET 4.5.

Thank you for any suggestion


回答1:


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.



来源:https://stackoverflow.com/questions/20904328/c-sharp-async-tasks-in-a-queue-or-waiting-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!