C# 由于连续链接而导致的等待任务

C# 由于连续链接而导致的等待任务,c#,asynchronous,async-await,task,continuewith,C#,Asynchronous,Async Await,Task,Continuewith,我将任务与ContinueWith链接,并等待它们全部完成。当我在循环中引入延迟(注释-这意味着有足够的时间完成任务)时,我可以看到所有任务都已完成。当我删除延迟时,我只能看到处理了第一条消息。未处理剩余的消息。我假设代码在完成所有任务之前退出方法。不确定我是否等待错了 我如何确保我的所有任务都完成了,而不会在循环中引入延迟 using (var throttler = new SemaphoreSlim(initialConcurrentJobsCount, maxConcurrentJobs

我将任务与ContinueWith链接,并等待它们全部完成。当我在循环中引入延迟(注释-这意味着有足够的时间完成任务)时,我可以看到所有任务都已完成。当我删除延迟时,我只能看到处理了第一条消息。未处理剩余的消息。我假设代码在完成所有任务之前退出方法。不确定我是否等待错了

我如何确保我的所有任务都完成了,而不会在循环中引入延迟

using (var throttler = new SemaphoreSlim(initialConcurrentJobsCount, maxConcurrentJobsCount))
{
     for(int counter = 0; counter < msgs.Length; counter++)
        {
            tasks[counter] = throttler.WaitAsync()
                                    .ContinueWith(r => new VirtualMachineActor().HandleAsync(msgs[counter]))
                                    .ContinueWith(o => throttler.Release());

                // When below line is present, all tasks are completed properly. 
                // When removed only first msg is executed.
                await Task.Delay(1000);  
       } 
       await Task.WhenAll(tasks);
}
使用(var throttler=new信号量lim(initialConcurrentJobScont,maxConcurrentJobScont))
{
用于(int计数器=0;计数器new VirtualMachineActor().HandleAsync(msgs[counter]))
.ContinueWith(o=>throttler.Release());
//当出现以下行时,所有任务都已正确完成。
//删除时,只执行第一个消息。
等待任务。延迟(1000);
} 
等待任务。何时(任务);
}

为了其他人的利益,“ContinueWith”链并不一定意味着任务执行的顺序。它是一个包装器,因此需要“展开”。

您不应该使用
ConinueWith
。改用
wait
。@StephenCleary,我已经根据你的评论更新了这个问题