问题
I had a method like that:
public async Task<IEnumerable<Model>> Get(string link)
{
MyRequestAsync request = new MyRequestAsync(link);
return await request.GetResult();
}
It is working pretty well.
Then I decided to change this one a little bit:
public async Task<IEnumerable<Model>> Get([FromUri]IList<string> links)
{
IList<Model> list = new List<Model>();
foreach (var link in links)
{
MyRequestAsync request = new MyRequestAsync(link);
list.Add(await request.GetResult());
}
return list;
}
And now I am got a problem, for some reason it is just not returning the result. For my understanding I am getting the deadlock.
Do you know how to fix that?
回答1:
Add ConfigureAwait(false) to not deadlock on the UI Thread.
public async Task<IEnumerable<Model>> Get([FromUri]IList<string> links)
{
IList<Model> list = new List<Model>();
foreach (var link in links)
{
MyRequestAsync request = new MyRequestAsync(link);
list.Add(await request.GetResult().ConfigureAwait(false));
}
return list;
回答2:
Give this a try:
IList<Model> list = new List<Model>();
to
ConcurrentBag<Model> list = new ConcurrentBag<Model>();
Often times using async and await can get confusing (for me, at least) and will produce results that I'm unsure of. This is the first thing I swap out when I have trouble.
http://msdn.microsoft.com/en-us/library/dd381779(v=vs.110).aspx
来源:https://stackoverflow.com/questions/23134243/async-issue-when-changed-method-to-use-collection