异步处理 IEnumerable<Task>,并发性有限

Mar*_*ijn 5 c# concurrency asynchronous task-parallel-library async-await

我有一个IEnumerable<Task<T>>whereT代表某个事件(事件的自然语言类型,而不是event事件的类型)。

我想异步处理这些,因为它们是 IO 绑定的,并限制并发量,因为处理事件的数据库无法处理超过少数(例如 6)个并发处理请求(它们相当重)什么是这样做的正确策略是什么?

如果我有

private Task processeventasync(T someevent) {
  ...
}

foreach(t in tasks) {
  await processeventsasync(await t)
}
Run Code Online (Sandbox Code Playgroud)

我没有并发。

如果我用信号量保护事物,我实际上是在保护线程并用锁保护它们,而不是异步等待它们。

https://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(v=vs.110).aspxLimitedConcurrencyLevelTaskScheduler上的示例也是基于线程/锁的方法

我考虑过维护一个最多 6 个任务的队列,并WhenAny围绕它进行循环,但这感觉就像重新发明方轮。

private List<Task> running = new List<Task>();

foreach(Task<T> task in tasks) {
  var inner = TaskExtensions.Unwrap(t.ContinueWith(tt => processeventasync(tt.Result)));
  running.Add(inner);
  if (running.Count >= 6) {
    var resulttask = await Task.WhenAny(running); 
    running.Remove(resulttask);
    await resulttask;
    //not sure if this await will schedule the next iteration
    //of the loop asynchronously, or if the loop happily continues
    //and the continuation has the rest of the loop body (nothing
  }
}
Run Code Online (Sandbox Code Playgroud)

去这里的正确方法是什么?

编辑:

SemaphoreSlimsWaitAsync对此似乎非常合理。我看到以下看起来很奇怪的代码:

    private async void Foo()
    {

        IEnumerable<Task<int>> tasks = gettasks();
        var resulttasks = tasks.Select(ti => TaskExtensions.Unwrap(ti.ContinueWith(tt => processeventasync(tt.Result))));
        var semaphore = new SemaphoreSlim(initialCount: 6);

        foreach (Task task in resulttasks)
        {
            await semaphore.WaitAsync();
            semaphore.Release();
        }
    }
Run Code Online (Sandbox Code Playgroud)

拥有async void这里虽然有点臭,但它是一个无限循环;它永远不会返回(实际处理显然会有一些取消机制)。

仅在正文中等待/释放看起来确实很奇怪,但看起来实际上是正确的。这是没有隐藏陷阱的合理方法吗?

Yuv*_*kov 3

您可以使用限制并发SemaphoreSlim.WaitAsync

仅在正文中等待/释放看起来很奇怪,但看起来实际上是正确的

您当前的方法实际上没有任何作用。这些任务根本不受 影响SemaphoreSlim,因为您同时使用 调用它们Enumerable.Select

您需要监视以下信号量Select

private const int ConcurrencyLimit = 6;
SemaphoreSlim semaphoreSlim = new SemaphoreSlim(ConcurrencyLimit);

public async Task FooAsync()
{
    var tasks = GetTasks();
    var sentTasks = tasks.Select(async task =>
    {
       await semaphoreSlim.WaitAsync();
       try
       {
          await ProcessEventAsync(await task);
       }
       finally
       {
           semaphoreSlim.Release();
       }
    });

    await Task.WhenAll(sentTasks);
}

private Task ProcessEventAsync(T someEvent) 
{
    // Process event.
}
Run Code Online (Sandbox Code Playgroud)