在队列或等待列表C#异步任务 [英] C# async tasks in a queue or waiting list

查看:244
本文介绍了在队列或等待列表C#异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个异步任务是这样的:

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

现在我的问题:

什么`以启动任务并仅运行它们的3,在同一时间(直到他人正在等待)的最佳方式

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使用.NET 4.5。

I`am using .NET 4.5.

感谢您的任何建议。

推荐答案

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

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

节流任务的一个选择是<一个href=\"http://msdn.microsoft.com/en-us/library/system.threading.semaphoreslim%28v=vs.110%29.aspx\"><$c$c>SemaphoreSlim,你可以这样使用:

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

另一种选择是使用一个实际的队列,像<一个href=\"http://msdn.microsoft.com/en-us/library/hh194684%28v=vs.110%29.aspx\"><$c$c>ActionBlock<T>,它有内置的限制支持。

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

这篇关于在队列或等待列表C#异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆