異步方法返回Task
。如果您不使用Wait()
,代碼會繼續執行超過異步方法。如果您不想使用Wait()
,則可以使用Callback
-method作爲參數創建異步方法。
有等待(注):
// Asynchronous download method that gets a String
public async Task<string> DownloadString(Uri uri) {
var task = new TaskCompletionSource<string>();
try {
var client = new WebClient();
client.DownloadStringCompleted += (s, e) => {
task.SetResult(e.Result);
};
client.DownloadStringAsync(uri);
} catch (Exception ex) {
task.SetException(ex);
}
return await task.Task;
}
private void TestMethod() {
// Start a new download task asynchronously
var task = DownloadString(new Uri("http://mywebsite.com"));
// Wait for the result
task.Wait();
// Read the result
String resultString = task.Result;
}
或者有回調:
private void TestMethodCallback() {
// Start a new download task asynchronously
DownloadString(new Uri("http://mywebsite.com"), (resultString) => {
// This code inside will be run after asynchronous downloading
MessageBox.Show(resultString);
});
// The code will continue to run here
}
// Downlaod example with Callback-method
public async void DownloadString(Uri uri, Action<String> callback) {
var client = new WebClient();
client.DownloadStringCompleted += (s, e) => {
callback(e.Result);
};
client.DownloadStringAsync(uri);
}
當然我建議使用回調的方式,因爲它沒有阻止代碼在下載String
時運行。
您是否嘗試過使用異步API?至少發佈你的'getStringFromWeb'方法調用。 –
使用HttpClient和async/await關鍵字,可以編寫非常類似於編寫同步代碼的異步代碼。它會爲您節省很多時間來轉換您的代碼 –
感謝關鍵字KooKiz,這是我正在尋找的解決方案。 – donkz