c# async/await编程
今天整理了一下c#異步編程的資料。
public partial class MainWindow : Window
? ? {
? ? ? ??
? ? ? ? private async void StartButton_Click(object sender, RoutedEventArgs e)
? ? ? ? {
? ? ? ? ? ? resultsTextBox.Text += "begin to invoke AccessTheWebAsync...\r\n";
? ? ? ? ? ? //方式1:調用和await分開
? ? ? ? ? ? Task<int> getLengthTask = AccessTheWebAsync();
? ? ? ? ? ? resultsTextBox.Text += "do other works ...\r\n";
? ? ? ? ? ? int contentLength = await getLengthTask;
? ? ? ? ? ? //方式2:調用和await不分開
? ? ? ? ? ? //int contentLength = await AccessTheWebAsync();
? ? ? ? ? ? resultsTextBox.Text += ?String.Format("Length of the downloaded string: {0}.\r\n", contentLength);
? ? ? ? }
? ? ? ? async Task<int> AccessTheWebAsync()
? ? ? ? {
? ? ? ? ? ? resultsTextBox.Text += "AccessTheWebAsync...\r\n";
? ? ? ? ? ? HttpClient client = new HttpClient();
? ? ? ? ? ? Task<string> getStringTask = client.GetStringAsync("https://www.baidu.com");
? ? ? ? ? ? DoIndependentWork();
? ? ? ? ? ? //等待返回, 向上層交還控制權
? ? ? ? ? ? string urlContents = await getStringTask;
? ? ? ? ? ? resultsTextBox.Text += "GetStringAsync return ...\r\n";
? ? ? ? ? ? //返回結果
? ? ? ? ? ? return urlContents.Length;
? ? ? ? }
? ? ? ? void DoIndependentWork()
? ? ? ? {
? ? ? ? ? ? resultsTextBox.Text += "Working . . . . . . .\r\n";
? ? ? ? }
? ? }
運行效果
總結
以上是生活随笔為你收集整理的c# async/await编程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MongoDB集群分片部署指南
- 下一篇: maven使用OracleDB jdbc