Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 497
SurenSaluka Avatar asked Feb 09 '23 16:02

SurenSaluka


1 Answers

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.

like image 180
i3arnon Avatar answered Mar 03 '23 16:03

i3arnon