简体   繁体   English

多个异步任务

[英]Multiple Async Tasks

I have two async mehotds that not directly related to one another (they do both write out though).. and i don't want either to block the efficiency of the other.. 我有两个彼此不直接相关的异步方法(尽管它们都写了)..我也不想阻止任何一个的效率。

If i place one of the activities in a set of tasks like this: 如果我将一项活动放在这样的一组任务中:

var list = new List<Task>();

foreach (var t in things)
{
    list.Add(My.MethodAsync(t)); // method returns Task
}

await Task.WhenAll(t);

I know that it will not block, and potentially run in parallel.. 我知道它不会阻塞,并且可能并行运行。

If i another async method though though: 如果我不过是另一种异步方法:

var list = new List<Task>();

foreach (var t in things)
{
    list.Add(My.MethodAsync(t)); // method returns Task
}

foreach (var t in things)
{
    await My.OtherAsync(t)); // method returns Task
}

await Task.WhenAll(t);

The Task.WhenAll() needs to wait for the second foreach to complete... Task.WhenAll()需要等待第二个foreach完成...

Therefore, is something like this possible / recommend? 因此,这样的事情可能/建议吗?

var allTasks = new List<Task>();

foreach (var t in things)
{
    allTasks.Add(My.MethodAsync(t)); // method returns Task
    allTasks.Add(My.OtherAsync(t)); // method returns Task
}

await Task.WhenAll(t);

Having typed this out, even though the tasks themselves are independent, it would be nice i guess if an error was raised if both do not output.. hmm 输入了这些内容后,即使任务本身是独立的,如果两个都没有输出,我想如果出现错误也会很好。

question still stands though ;) 问题仍然存在;)

var allTasks = new List<Task>();

foreach (var t in things)
{
    allTasks.Add(My.MethodAsync(t); // method returns Task
    allTasks.Add(My.OtherAsync(t); // method returns Task
}

await Task.WhenAll(t).ConfigureAwait(false);

This will work just fine. 这样就可以了。 As was pointed out in the comments, if your methods return a Task that was started already (see here ), then all Task.WhenAll will do is wait asynchronously for the tasks to complete. 如注释中所指出的,如果您的方法返回一个已经启动的Task (请参阅此处 ),那么所有Task.WhenAll都将异步地等待任务完成。 These tasks may run in parallel if their run-time is long enough that you can start one before the previous finishes. 如果这些任务的运行时间足够长,您可以在上一个任务完成之前启动它们,则这些任务可以并行运行。 Note that I added ConfigureAwait(false) to your code. 请注意,我在您的代码中添加了ConfigureAwait(false) Technically, it doesn't actually change what your code is doing as await is done with false as the default but it does clarify your intent so I prefer it when I write asynchronous method calls. 从技术上讲,它实际上并不会更改代码的行为,因为默认情况下使用false作为默认值来完成await ,但是它确实阐明了您的意图,因此在编写异步方法调用时我更喜欢它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM