如何同时 运行 2 个异步函数
How to run 2 async functions simultaneously
我需要知道如何同时 运行 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.
}
这里我有 2 个 CreateRequest()
方法,它们依次 运行s。我想 运行 这两个函数并行并且在两个函数的末尾我想 return 结果。
我该如何实现?
如果您只需要 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
创建一个任务,该任务将在所有提供的任务中的第一个任务完成时完成。它 returns 完成的一项任务,因此您可以获得其结果。
我需要知道如何同时 运行 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.
}
这里我有 2 个 CreateRequest()
方法,它们依次 运行s。我想 运行 这两个函数并行并且在两个函数的末尾我想 return 结果。
我该如何实现?
如果您只需要 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
创建一个任务,该任务将在所有提供的任务中的第一个任务完成时完成。它 returns 完成的一项任务,因此您可以获得其结果。