0

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?

Sergino
  • 10,128
  • 30
  • 98
  • 159
  • possible duplicate of [Is it possible to "await yield return DoSomethingAsync()"](http://stackoverflow.com/questions/5061761/is-it-possible-to-await-yield-return-dosomethingasync) – Fals Apr 17 '14 at 13:22
  • 1
    @Fals, doesn't seem related. He's not using yield. – Matt Smith Apr 17 '14 at 13:32
  • 1
    If you posted a small but complete example that reproduced the problem, we'd be able to help you better. – Matt Smith Apr 17 '14 at 13:35
  • Pause the debugger to see what's on the stack. Were does execution halt? Probably some blocking code in `GetResult`. – usr Apr 17 '14 at 13:42
  • Your first method won't even compile, so how come you say it's working? – svick Apr 17 '14 at 14:15
  • It doesn't look like a deadlock, try passing in a list of just one url and see what happens. – NeddySpaghetti Apr 18 '14 at 08:05

2 Answers2

0

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;
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
-3

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

Ian P
  • 12,840
  • 6
  • 48
  • 70
  • I don't think that [cargo cult programming](http://en.wikipedia.org/wiki/Cargo_cult_programming) (“I don't know what this does, but it worked for me once, so it may work for you too, even if the situation is different”) is a good practice. And I don't see any reason why this change should help here. – svick Apr 17 '14 at 14:17