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();
It's unlikely but possible that this code could cause a deadlock. As described on my blog, the classic deadlock requires two parts:
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.