1
votes

I'm new to c# async await mechanism. I read some articles about async all the way (http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html). I have an example below, could you please let me know if the first Initialize method will cause dead lock and why? Thank you in advance.

public class Test {

    public  async  Task DoSomeWorkAsync() {
      await DoSomeWork1Async(); 
    }

    // This method is mixed with Wait and async await, will this cause lead lock?
    public void Initialize() {
      Task.Run(() => DoSomeWorkAsync()).Wait();
    }

    // This method is following async all the way
    public async Task InitializeAsync()  {
      await DoSomeWorkAsync();
    }

}

// Update: Here is the context where two Initialize methods are called
public class TestForm : Form {
  // Load Form UI
  public async void OnLoad() {
    var test = new Test();
    test.Initialize();
    await test.InitializeAsync();
  }
}
1
It depends on context where you are using it. - Hamlet Hakobyan
In the Initialize() method, I would simply do DoSomeWorkAsync().Wait(). Using Task.Run() will start a new thread and call DoSomeWorkAsync() synchronously. - Philippe Paré
thanks guys I added context where they are being used. - macio.Jun
@PhilippeParé: thx Philippe, but will DoSomeWorkAsync().Wait() cause dead lock? I assume async-await all the way down means once you use asyn-await, you can't mix Wait(). Please Correct me if I'm wrong. - macio.Jun
@PhilippeParé no. It will deadlock as in it will get stuck forever. - i3arnon

1 Answers

6
votes

No, this will not deadlock because you're blocking on a task that's being executed by a ThreadPool thread with no SynchronizationContext. Since it isn't running on the UI thread there's nothing stopping that task from completing and so there's no deadlock.

If this was your code, it will have deadlocked:

public void Initialize()
{
    DoSomeWorkAsync().Wait();
}

This is still not a good reason to block though, you should use async-await all they way up.