Why can't Task.Result be modified to not deadlock?
As many of us have found over the years, one should avoid mixing synchronous code with asynchronous code, as it readily results in deadlocks. Here is a classic example (source):
// My "library" method. public static async Task<JObject> GetJsonAsync(Uri uri) { using (var client = new HttpClient()) { var jsonString = await client.GetStringAsync(uri); return JObject.Parse(jsonString); } } // My "top-level" method. public void Button1_Click(...) { var jsonTask = GetJsonAsync(...); textBox1.Text = jsonTask.Result; }
Something I've never seen explored (perhaps my Google-fu is lacking) is this: Why does Task<T>.Result have to result in a deadlock? It seems like the obvious solution is for it to unblock when there is code ready to run in that context, like a message pump. It would be unblocking itself, essentially, so it doesn't seem like there would be any pitfalls or opportunity for weirdness. What specifically prevents this from being a good solution?
0 comments:
Post a Comment