我是新來的c#異步等待機制。我讀了一些關於異步的文章(http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html)。我在下面有一個例子,如果第一個Initialize
方法會導致死鎖,請告訴我爲什麼?先謝謝你。異步一直等待異步
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();
}
}
這取決於您使用它的環境。 –
在'Initialize()'方法中,我會簡單地執行'DoSomeWorkAsync()。Wait()'。使用'Task.Run()'將啓動一個新線程並同步調用DoSomeWorkAsync()。 –
感謝球員我添加了他們正在使用的上下文。 –