Async and Await with HttpWebRequest.GetResponseAsync
I suspect that further up your call stack, you're either calling Wait
or Result
on the returned Task
. This will cause a deadlock, as I describe on my blog.
Follow these best practices to avoid the deadlock:
- Don't block on
async
code; useasync
all the way down. - In your "library" methods, use
ConfigureAwait(false)
.
John Koerner
Developer at Autodesk. (All posts are my own and do not represent ... blah blah blah...) C#, Java, JavaScript, and whatever else I need to get the job done. Twitter: @JohnKoerner
Updated on July 09, 2022Comments
-
John Koerner almost 2 years
I am trying to use Async and Await when making a web request and am finding that it never gets past the await line. I am doing this from a Metro app, but I also verified the problem in a winforms app.
public async Task<string> DoSomething() { string url = "http://imgur.com/gallery/VcBfl.json"; HttpWebRequest request = HttpWebRequest.CreateHttp(url); var ws = await request.GetResponseAsync(); return ws.ResponseUri.ToString(); ; }
If I don't use await and instead perform a synchronous wait, it works, but I need this to run asynchronously.
What am I missing in this code that is causing the await to never return?