0

We all now know that the following can cause a deadlock:

var result = myFunctionAsync().Result;

But what about:

var task = myFunctionAsync();
Task.WaitAll(task);
var result = task.Result;

Will this pattern prevent any deadlocks?

Neil
  • 11,059
  • 3
  • 31
  • 56
  • 1
    The *pattern* is to not block. Both snippets block and hence, both can cause deadlocks in the right conditions – Panagiotis Kanavos Oct 16 '19 at 11:13
  • Note that it's the `Task.WaitAll` which can deadlock in your second example, not the `task.Result` – canton7 Oct 16 '19 at 11:14
  • In fact, the second is nothing more than an elaborate `.Result` in multiple steps. `Task.Result` calls `Task.Wait()`. So does `Task.WaitAll()` though – Panagiotis Kanavos Oct 16 '19 at 11:14
  • What is the *real* question and the actual code? Why not use `var result=await myFunctionAsync();`? – Panagiotis Kanavos Oct 16 '19 at 11:15
  • I'm trying to fix a massive project that has mostly done async incorrectly (lots of async.Result patterns) and is now regularly deadlocking. Mostly I can make the whole call tree async, but there are some cases where this is not possible (for a bad example, in a property that uses an async function). – Neil Oct 16 '19 at 11:17
  • You can check the discussion regarding async Property at [this](https://stackoverflow.com/questions/6602244/how-to-call-an-async-method-from-a-getter-or-setter) stackoverflow thread. As mentioned by you too I would suggest that you should make the whole call tree async. – user1672994 Oct 16 '19 at 11:31
  • @user1672994 Properties can't be `async` – Neil Oct 16 '19 at 11:31
  • 1
    Agree, it can not be `async`. Please check the mentioned SO thread which talks about the approaches. – user1672994 Oct 16 '19 at 11:32
  • @Neil a property can return `Lazy` and thus be async. Not because the getter/setter itself is async, but because the *method* use to produce the value will run asynchronously, at the time it's requested. That won't solve every problem though. You'll have to post specific examples. Different problems may have the same symptoms but require different solutions. – Panagiotis Kanavos Oct 16 '19 at 11:45

0 Answers0