1:使用async和await异步编程
常用使用场景如下:
Web 访问 | HttpClient | SyndicationClient |
使用文件 | StreamWriter, StreamReader, XmlReader | StorageFile |
使用图像 | MediaCapture, BitmapEncoder, BitmapDecoder | |
WCF 编程 | 同步和异步操作 |
方法名前加async编程异步方法,方法返回类型 task task<TResult> void,需要使用异步方法结果用await 等待异步返回的结果;没有用await异步方法会作为同步方法执行。
async和await不会创建新线程,也不会阻止当前线程,异步方法不会在自身线程上运行,异步设计原理就是非阻塞操作,await等待的时候呢,会把操作权返回给调用方。
调用async方法的时候会在后台去线程池里调用闲置的线程执行方法,await就会挂起等待当前异步方法返回结果。
2:使用Task.WhenAll扩展异步方法
当有多个异步需要执行到时候,可以使用Task.WhenAll执行异步集合,当所有异步方法在里面执行完后,Task.WhenAll才会结束。
C#复制
// Create a query. IEnumerable<Task<int>> downloadTasksQuery = from url in urlList select ProcessURL(url, client); // Use ToArray to execute the query and start the download tasks. Task<int>[] downloadTasks = downloadTasksQuery.ToArray();
// Await the completion of all the running tasks.
int[] lengths = await Task.WhenAll(downloadTasks);
3:使用Async和Await并行发起web请求
就是在使用await前,在启动任务和等待任务之间可以发起多次请求。其它任务都会以隐式的方式运行,不会创建新线程。
C#复制
private async Task CreateMultipleTasksAsync()
{
// Declare an HttpClient object, and increase the buffer size. The
// default buffer size is 65,536.
HttpClient client =
new HttpClient() { MaxResponseContentBufferSize = 1000000 };
// Create and start the tasks. As each task finishes, DisplayResults
// displays its length.
Task<int> download1 =
ProcessURLAsync("http://msdn.microsoft.com", client);
Task<int> download2 =
ProcessURLAsync("http://msdn.microsoft.com/library/hh156528(VS.110).aspx", client);
Task<int> download3 =
ProcessURLAsync("http://msdn.microsoft.com/library/67w7t67f.aspx", client);
// Await each task.
int length1 = await download1;
int length2 = await download2;
int length3 = await download3;
int total = length1 + length2 + length3;
// Display the total count for the downloaded websites.
resultsTextBox.Text +=
string.Format("\r\n\r\nTotal bytes returned: {0}\r\n", total);
}
4:异步控制流
用到关键字await异步就将控制器返回调用方。
C#复制
public partial class MainWindow : Window
{
// . . .
private async void startButton_Click(object sender, RoutedEventArgs e)
{
// ONE
Task<int> getLengthTask = AccessTheWebAsync();
// FOUR
int contentLength = await getLengthTask;
// SIX
resultsTextBox.Text +=
String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
}
async Task<int> AccessTheWebAsync()
{
// TWO
HttpClient client = new HttpClient();
Task<string> getStringTask =
client.GetStringAsync("http://msdn.microsoft.com");
// THREE
string urlContents = await getStringTask;
// FIVE
return urlContents.Length;
}
}
5:微调异步应用程序
1. 取消一个异步任务或者一组异步任务
不想等待一个异步任务完成,可以通过设置来取消该任务。
取消单个和取消列表类似:
C#复制
// ***Declare a System.Threadin