简体   繁体   English

如何同时运行2个异步函数

[英]How to run 2 async functions simultaneously

I need to know how to run 2 async functions simultaneously, for an example check the following code: 我需要知道如何同时运行2个异步函数,例如检查以下代码:

public async Task<ResponseDataModel> DataDownload()
{
  ResponseDataModel responseModel1 = await RequestManager.CreateRequest(postData);
  ResponseDataModel responseModel2 = await RequestManager.CreateRequest(postData);

  //Wait here till both tasks complete. then return the result.

}

Here I have 2 CreateRequest() methods which runs sequentially. 这里我有2个CreateRequest()方法,它们按顺序运行。 I would like to run these 2 functions parallel and at the end of both functions I want to return the result. 我想并行运行这两个函数,并且在两个函数的末尾我想返回结果。 How do I achieve this? 我该如何实现这一目标?

If you only need the first result out of the 2 operations you can so that by calling the 2 methods, and awaiting both tasks together with `Task.WhenAny: 如果你只需要2个操作中的第一个结果,你可以通过调用2个方法,然后和`Task.WhenAny一起等待这两个任务:

public async Task<ResponseDataModel> DataDownloadAsync()
{
    var completedTask = await Task.WhenAny(
        RequestManager.CreateRequest(postData), 
        RequestManager.CreateRequest(postData));
    return await completedTask;
}

Task.WhenAny creates a task that will complete when the first task of all of the supplied tasks completed. Task.WhenAny创建一个任务,该任务将在所有提供的任务的第一个任务完成时完成。 It returns the one task that completed so you can get its result. 它返回完成的一个任务,以便您可以获得其结果。

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

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