[英]Async - wait for two async tasks to finish
I have two function calls that are run in my code, and when both are done, the function ProcessFiles is run. 我有两个在我的代码中运行的函数调用,当两者都完成后,运行ProcessFiles函数。 Like this: 像这样:
byte[] file1 = doSomething();
byte[] file2 = doSomethingElse();
ProcessFiles(file1, file2);
These two functioncalls DoSomething
and DoSomethingElse
are completely seperate, and I was thinking of running these in a different thread so they are run simultaneously. 这两个函数调用DoSomething
和DoSomethingElse
是完全独立的,我想在不同的线程中运行它们,以便它们同时运行。 However, I need to process the results (file1 and file2) when both are done. 但是,当两者都完成时,我需要处理结果(file1和file2)。
I guess async await (or its VB.NET equivalent) is the way to go here, but for the life of me, I can't find any good examples that showcase this. 我想异步等待(或其VB.NET等价物)是这里的方式,但对于我的生活,我找不到任何展示这个的好例子。 Maybe I'm using the wrong search queries, but so far I haven't been able to get a good example. 也许我使用了错误的搜索查询,但到目前为止我还没有得到一个好的例子。 Can anyone point me in the right direction please? 有人能指出我正确的方向吗?
Yes, you can do this easily with async/await. 是的,您可以使用async / await轻松完成此操作。 For example: 例如:
// If you don't have async equivalents, you could use Task.Run
// to start the synchronous operations in separate tasks.
// An alternative would be to use Parallel.Invoke
Task<byte[]> task1 = DoSomethingAsync();
Task<byte[]> task2 = DoSomethingElseAsync();
byte[] file1 = await task1;
byte[] file2 = await task2;
ProcessFiles(file1, file2);
The important thing is that you don't await either task until you've started both of them. 重要的是,在你启动这两项任务之前,你不会等待任何一项任务。
I was thinking of running these in a different thread... I guess async await 我想在不同的线程中运行这些...我想异步等待
Note that async
/ await
does not imply any particular kind of threading. 请注意, async
/ await
并不意味着任何特定类型的线程。 Async/await deals with asynchronous code, not parallel code. Async / await处理异步代码,而不是并行代码。 For more information, see my async
intro . 有关更多信息,请参阅我的async
介绍 。
However, you can use Task.Run
to execute code on a thread pool thread, and then you can use Task.WhenAll
to (asynchronously) wait for them both to complete: 但是,您可以使用Task.Run
在线程池线程上执行代码,然后您可以使用Task.WhenAll
(异步)等待它们完成:
var task1 = Task.Run(() => doSomething());
var task2 = Task.Run(() => doSomethingElse());
var results = await Task.WhenAll(task1, task2);
ProcessFiles(results[0], results[1]);
Alternatively, since your code is already synchronous, you can use WaitAll
. 或者,由于您的代码已经是同步的,因此您可以使用WaitAll
。 Note that your error handling is different with parallel code (you need to be prepared for AggregateException
): 请注意,您的错误处理与并行代码不同(您需要为AggregateException
做好准备):
var task1 = Task.Run(() => doSomething());
var task2 = Task.Run(() => doSomethingElse());
Task.WaitAll(task1, task2);
ProcessFiles(task1.Result, task2.Result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.