欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

浅谈.NET Core中的异步编程

程序员文章站 2022-03-09 13:40:49
...

什么是异步编程

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

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


异步编程的好处

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

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

.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.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;  
}
相关标签: c# asp.net