The call to Result
in your foreach
loop is causing a deadlock, as I explain on my blog. In summary, await
will capture a "context" (e.g., a UI context), and use that to resume the async
method. Some contexts (e.g., the UI context) only allow one thread in the context. So if you block that special thread (e.g., the UI thread) by calling Result
, then the async
method cannot resume execution within that context.
So, the solution is to change your foreach
loop:
foreach(var url in myUrlList)
{
string body = await ProcessAsync(method);
}
Other notes:
Task-returning methods should end in "Async" to follow the TAP guidelines.
Task.Factory.FromAsync
is unnecessary; HttpWebRequest
already has awaitable methods. An even better option is to use HttpClient
instead.
I recommend that you not use Task.ContinueWith
(or Task.Result
, or Task.Wait
); use await
instead.
With these simplifications in place:
private async Task<string> MakeAsyncRequestAsync(string url, string contentType)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = WebRequestMethods.Http.Get;
request.Timeout = 20000;
request.Proxy = null;
WebResponse response = await request.GetResponseAsync();
return ReadStreamFromResponse(response);
}
This code could be simplified further if you change HttpWebRequest
to HttpClient
.