.Net Core异步编程

什么是异步编程?

同步程序中的代码运行在单一线程上。

异步操作:从其它线程发起后,在一个新的单独线程上运行的操作。发起异步操作的线程不必等待异步操作完成

为什么使用异步编程?
对于需要长时间运行的操作,异步编程可以更大限度更有效地利用设备资源。

通过异步执行 CPU 或 I/O 绑定操作,提高 UI 程序的响应性

并行计算

最适合应用异步编程的程序
桌面 UI 程序

WinForms
WPF
UWP
Web Server 程序

异步编程不是万能的
不要无脑使用异步,有些问题异步也无法解决,而且异步本身也会带来一些问题:

异步代码自身不带来任何的性能提升。它只让资源管理更高效异步代码给程序带来更大的开销

.NET 内置的异步方法
async 和 await 关键字

async 和 await 是 C# 异步编程的核心,由它们定义的方法称为异步方法

// 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.microsoft.com");  
	// You can do work here that doesn't rely on the string from GetStringAsync.  
	DoIndependentWork();  
	// The await operator suspends AccessTheWebAsync.     
	//  - AccessTheWebAsync can't continue until getStringTask is complete.      
	//  - Meanwhile, control returns to the caller of AccessTheWebAsync.      
	//  - Control resumes here when getStringTask is complete.       
	//  - The await operator then retrieves the string result from getStringTask.      
	string urlContents = await getStringTask;  
	// The return statement specifies an integer result.      
	// Any methods that are awaiting AccessTheWebAsync retrieve the length value.      
	return urlContents.Length;  
}

await 表达式的意思是:方法在此处需要等待异步操作完成后才能继续向下执行。同时方法将被挂起,控制流返回给方法的调用者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值