什么是异步编程
同步程序中的代码是运行在单一线程上的。
异步操作:从其它线程发起后,在一个新的单独线程上运行的操作。发起异步操作的线程不必等待异步操作完成。
异步编程的好处
对于需要长时间运行的操作,异步编程可以更大限度更有效地利用设备资源。
- 通过异步执行 CPU 或 I/O 绑定操作,提高 UI 程序的响应性
- 并行计算
.NET内置的异步方法
// Three things to note in the signature:
// - The method has an async modifier.
// - The return type is Task or Task<T>.
// Here, it is Task<int> because the return statement returns an integer.
// - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();
// GetStringAsync returns a Task<string>. That means that when you await the task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync("http://msdn.micro