我有多个异步方法,可以一一运行,但是当我使用Task.WhenAll时,我真的不知道如何获得结果。以下是我的异步方法
public async Task<IEnumerable<MyModel>> Method1Async()
{
return await Task<IEnumerable<MyModel>>.Run<IEnumerable<MyModel>>(() => GetMethod1Data());
}
//Here Method1Async().Result will get me the data but don't know how to get the result when I am using Task.WhenAll()
public async Task<IEnumerable<MyModel>> Method2Async()
{
return await Task<IEnumerable<MyModel>>.Run<IEnumerable<MyModel>>(() => GetMethod2Data());
}
public async Task<IEnumerable<MyModel>> Method3Async()
{
return await Task<IEnumerable<MyModel>>.Run<IEnumerable<MyModel>>(() => GetMethod3Data());
}
这是我使用Task.WhenAll的代码
public async Task GetDataAsync()
{
Task[] tasks = new Task[3];
tasks[0] = Method1Async();
tasks[1] = Method2Async();
tasks[2] = Method2Async();
await Task.WhenAll(tasks).ConfigureAwait(false);
}
现在,如果我打电话
GetDataAsync()
方法,我一切都很好,但是不知道如何从返回的任务中得到结果?
答案 0 :(得分:0)
它将返回类型为IEnumerable<MyModel>
的数组,因此您可以将异步方法的返回类型设置为:
public Task<IEnumerable<MyModel>[]> GetDataAsync()
{
Task[] tasks = new Task[3];
tasks[0] = staticDataService.Method1Async();
tasks[1] = staticDataService.Method2Async();
tasks[2] = staticDataService.Method3Async();
return Task.WhenAll(tasks);
}
然后食用它:
IEnumerable<MyModel>[] results = await GetDataAsync();