C# & WPF 隨手小記之一 ——初探async await 實現多線程處理


嗯。。。我也是在園子待了不短時間的人了,一直以來汲取着園友的知識,感覺需要回饋什么。

於是以后有空我都會把一些小技巧小知識寫下來,有時候可能會很短甚至很簡單,但希望能幫到大家咯。

第一篇文章來說說async 和 await吧。

這是微軟關於Async的介紹:http://msdn.microsoft.com/en-us/library/hh156513.aspx

這是await :http://msdn.microsoft.com/en-us/library/hh156528.aspx

這是綜合起來講:http://msdn.microsoft.com/en-us/library/hh191443.aspx

 

async和await用起來並不是很難,大部分人是這么用的,微軟的sample是這么寫的:

private async void StartButton_Click(object sender, RoutedEventArgs e)
{
    // ExampleMethodAsync returns a Task<int>, which means that the method
    // eventually produces an int result. However, ExampleMethodAsync returns
    // the Task<int> value as soon as it reaches an await.
    ResultsTextBox.Text += "\n";
    try
    {
        int length = await ExampleMethodAsync();
        // Note that you could put "await ExampleMethodAsync()" in the next line where
        // "length" is, but due to when '+=' fetches the value of ResultsTextBox, you
        // would not see the global side effect of ExampleMethodAsync setting the text.
        ResultsTextBox.Text += String.Format("Length: {0}\n", length);
    }
    catch (Exception)
    {
        // Process the exception if one occurs.
    }
}

public async Task<int> ExampleMethodAsync()
{
    var httpClient = new HttpClient();
    int exampleInt = (await httpClient.GetStringAsync("http://msdn.microsoft.com")).Length;
    ResultsTextBox.Text += "Preparing to finish ExampleMethodAsync.\n";
    // After the following return statement, any method that's awaiting
    // ExampleMethodAsync (in this case, StartButton_Click) can get the 
    // integer result.
    return exampleInt;
}
// Output:
// Preparing to finish ExampleMethodAsync.
// Length: 53292

上面是微軟給的寫法,給按鈕的響應方法加上async,然后await ExampleMethodAsync,讓一個Length變量來接收返回值。

 

但是其實async和await還有另一種用法:

        private async void button_Click(object sender, RoutedEventArgs e)
        {
            TB_Result.Text = await exampleAsync();
        }
        private async Task<string> exampleAsync()
        {
             return await Task.Run(() =>
             {
                 WebClient w = new WebClient();
                 w.DownloadFile("http://provissy.com", "webPage1");
                 w.DownloadFile("http://microsoft.com", "webPage2");
                 string a = w.DownloadString("http://microsoft.com");
                 return a;
             });
        }

Task.Run 和 Lambda表達式,用起來其實更加簡單。

在 => { }范圍內寫任何代碼都是異步執行的,因此不用擔心某幾個語句是否會長時間堵住UI線程。

當然,你不能訪問UI線程,否則會拋出異常。

 

如果不返回值,那就更簡單了

 

        private async Task exampleAsync()
        {
// 用 await exampleAsync(); 來調用即可,會立即返回。
await Task.Run(() => { WebClient w = new WebClient(); w.DownloadFile("http://provissy.com", "webPage1"); w.DownloadFile("http://microsoft.com", "webPage2"); });
}

 

 

 

好了就這么多,以后會盡量寫詳細點。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM