我似乎遇到了以下代码的死锁,但我不明白为什么
从代码中的某一点开始,我调用这个方法。
public async Task<SearchResult> Search(SearchData searchData)
{
var tasks = new List<Task<FolderResult>>();
using (var serviceClient = new Service.ServiceClient())
{
foreach (var result in MethodThatCallsWebservice(serviceClient, config, searchData))
tasks.Add(result);
return await GetResult(tasks);
}
其中GetResult如下:
private static async Task<SearchResult> GetResult(IEnumerable<Task<FolderResult>> tasks)
{
var result = new SearchResult();
await Task.WhenAll(tasks).ConfigureAwait(false);
foreach (var taskResult in tasks.Select(p => p.MyResult))
{
foreach (var folder in taskResult.Result)
{
// Do stuff to fill result
}
}
return result;
}
行var result = new SearchResult();
永远不会完成,尽管GUI由于以下代码而做出响应:
public async void DisplaySearchResult(Task<SearchResult> searchResult)
{
var result = await searchResult;
FillResultView(result);
}
此方法是通过调用Search方法的事件处理程序调用的。
_view.Search += (sender, args) => _view.DisplaySearchResult(_model.Search(args.Value));
调用DisplaySearchResult
的第一行,它沿着路径一直到具有Task.WhenAll(...)
部分的GetResult方法。
为什么Task.WhenAll(...)
一直没有完成?我没有正确理解wait的用法吗如果我同步运行任务,我确实会得到结果,但GUI会冻结:
foreach (var task in tasks)
task.RunSynchronously();
我阅读了各种解决方案,但大多数都与Task.WaitAll()
结合使用,因此没有太大帮助。正如你在DisplaySearchResult
中看到的那样,我也试图使用这篇博客文章的帮助,但我没能让它发挥作用。
更新1:方法MethodThatCallsWebservice
:
private IEnumerable<Task<FolderResult>> MethodThatCallsWebservice(ServiceClient serviceClient, SearchData searchData)
{
// Doing stuff here to determine keys
foreach(var key in keys)
yield return new Task<FolderResult>(() => new FolderResult(key, serviceClient.GetStuff(input))); // NOTE: This is not the async variant
}
由于您有GetStuff
(GetStuffAsync
)的异步版本,因此最好使用它,而不是将同步GetStuff
卸载到具有Task.Run
的ThreadPool
线程。这会浪费线程并限制可伸缩性。
async
方法返回一个"热"任务,因此不需要调用Start
:
IEnumerable<Task<FolderResult>> MethodThatCallsWebservice(ServiceClient serviceClient, SearchData searchData)
{
return keys.Select(async key =>
new FolderResult(key, await serviceClient.GetStuffAsync(input)));
}
在返回任务之前,您需要先启动任务。或者更好地使用Task.Run.
此:
yield return new Task<FolderResult>(() =>
new FolderResult(key, serviceClient.GetStuff(input)))
// NOTE: This is not the async variant
最好写成:
yield return Task.Run<FolderResult>(() =>
new FolderResult(key, serviceClient.GetStuff(input)));