Search code examples
c#windows-runtimewindows-store-appsasync-awaitwinrt-async

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?


Solution

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