简体   繁体   中英

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:

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. 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:

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. It returns the one task that completed so you can get its result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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