1

I am trying to use HttpClient.PutAsync() to upload several images to Windows Azure storage at the same time. The code snippet looks like:

Task<HttpResponseMessage> putThumbnail = httpclient.PutAsync(new Uri(ThumbnailSas), thumbcontent);

Task<HttpResponseMessage> putImage = httpclient.PutAsync(new Uri(ImageSas), imagecontent);

Task.WaitAll(new Task<HttpResponseMessage>[] {putThumbnail, putImage});

Strangely in this way the server does not return at all so Task.WaitAll will wait forever.

if I change the code using await, the server returns and I can get the result correctly.

HttpResponseMessage result = await httpclient.PutAsync(new Uri(ThumbnailSas), thumbcontent);

How can I batch upload images using HttpClient.PutAsync?

Eldorado
  • 1,503
  • 2
  • 10
  • 6
  • possible duplicate of [await vs Task.Wait - Deadlock?](http://stackoverflow.com/questions/13140523/await-vs-task-wait-deadlock) - I believe there is nothing in specific about PutAsync, but rather the fact you are synchronously waiting (`WaitAll`) for all results blocking completion of `PutAsync` calls. – Alexei Levenkov Sep 27 '13 at 17:21

1 Answers1

2

You shouldn't block on async code, as I describe on my blog.

In this case, you can use Task.WhenAll:

Task<HttpResponseMessage> putThumbnail = ...;
Task<HttpResponseMessage> putImage = ...;
await Task.WhenAll(putThumbnail, putImage);

Also see Figure 5 in my MSDN article on async best practices or the end of my async intro blog post.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810