Async issue when changed method to use collection

橙三吉。 提交于 2019-12-08 12:45:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!