asp.net.netmultithreadingc#-3.0

GetAwait().GetResult causes potential threading problems


I have a piece of C# .Net code need to be debugged to check if the use of GetAwaiter().GetResult(); could cause threading related problems. The suggestion I got was to replace it with async/await pattern, which I agree with. However, I am wondering if the original code could really cause a threading problem?

var client = new HttpClient();
var res = client.GetAsync(URL).GetAwaiter().GetResult();
var resData = await res.Content.ReadAsStringAsync();

Solution

  • It's unlikely but possible that this code could cause a deadlock. As described on my blog, the classic deadlock requires two parts:

    1. A one-thread-at-a-time synchronization context.
    2. Asynchronous code that uses that context to schedule its continuation.

    If either of these are missing, the deadlock does not happen. For example, if this code was running on a thread pool thread, then 1 wouldn't apply. And HttpClient code generally does not do 2, although there are some scenarios where is has done so (IIRC, on some mobile platforms). So: the code is probably fine but it depends.

    More generally, if you can change this to await, that's not a bad idea, because your app will use fewer threads as a result. Even if the blocking doesn't cause deadlock, it would cause inefficiency.