.net async/await异步方法调用讲解
异步方法不是降低单个方法的运行时间,而是能提高服务器整体并发量, 因为异步方法调用是线程切换的(await代码之前是一个线程,执行await代码线程返回线程池,await之后的代码从线程池重新分配线程执行),线程切换充分利用了每个线程资源,没有等待耗时任务的时间。
一、什么是同步方法、异步方法同步方法:程序按照编写顺序进行执行,在调用方法时线程会等待方法返回后再继续执行下一步;
异步方法:与同步方法相反,程序在执行方法时在方法尚未完成就返回调用方法继续执行,在调用方法继续执行的时候等待异步方法完成。
异步方法:用async关键字修饰的方法
1、异步方法的返回值一般是Task<T>,T是真正的返回值类型,Task<int>。惯例:异步方法名字以Async结尾。
2、即使方法没有返回值,也最好把返回值声明为非泛型的Task
3、调用异步方法时,一般在方法前面加上await关键字,这样拿到的返回值就是泛型指定的T类型。
4、异步方法的“传染性”:一个方法中如果有await调用,则这个方法也必须修饰为async。
二、异步方法调用
1、普通调用方式
1)无返回值方法调用
public async Task Test()
{
Show();
}
public async void Show()
{
string fileName = @"E:\a.txt";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++)
{
sb.AppendLine("hello");
}
await System.IO.File.ReadAllTextAsync(fileName);
}
2)有返回值调用
public async Task Test()
{
string s = await Show();
}
public async Task<string> Show()
{
string fileName = @"E:\a.txt";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++)
{
sb.AppendLine("hello");
}
string s = await System.IO.File.ReadAllTextAsync(fileName);
return s;
}
2、调用方法无法写Task修饰调用
1)无返回值调用
public void TestNoReturn()
{
Show();
}
public void ShowNoReturn()
{
string fileName = @"E:\a.txt";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++)
{
sb.AppendLine("hello");
}
System.IO.File.ReadAllTextAsync(fileName).Wait();
};
2)有返回值调用
public void Test()
{
string s = Show();
}
public string Show()
{
string fileName = @"E:\a.txt";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++)
{
sb.AppendLine("hello");
}
string s = System.IO.File.ReadAllTextAsync(fileName).Result;
return s;
}
3、lambda调用,Lamda表达式里面调用异步方法,在Lamda表达式开头加async也可以。
public ActionResult Index()
{
string s1 = Show2();
return View();
}
public static string Show2()
{
string fileName = @"E:\a.txt";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++)
{
sb.AppendLine("hello");
}
Thread.Sleep(3000);
ThreadPool.QueueUserWorkItem(async (obj) => {
while (true) {
await System.IO.File.WriteAllTextAsync(fileName, sb.ToString());
}
});
return s;
}
猜您可能还喜欢
评论列表
发表评论
文章分类
文章归档
- 2025年3月 (1)
- 2024年6月 (2)
- 2024年5月 (2)
- 2024年4月 (4)
- 2024年3月 (30)
- 2024年1月 (4)
- 2023年12月 (2)
- 2023年11月 (4)
- 2023年10月 (4)
- 2023年9月 (6)
- 2023年3月 (2)
- 2023年2月 (1)
- 2023年1月 (1)
- 2022年12月 (1)
- 2022年9月 (21)
- 2022年8月 (10)
- 2022年7月 (3)
- 2022年4月 (1)
- 2022年3月 (13)
- 2021年8月 (1)
- 2021年3月 (1)
- 2020年12月 (42)
- 2020年11月 (7)
- 2020年10月 (5)
- 2020年8月 (1)
- 2020年6月 (1)
- 2020年3月 (2)
- 2019年12月 (8)
- 2019年11月 (3)
- 2019年9月 (1)
- 2019年4月 (1)
- 2019年3月 (6)
- 2019年2月 (1)
- 2018年7月 (7)
阅读排行
- 1.asp.net mvc内微信pc端、H5、JsApi支付方式总结(5876)
- 2.Windows 10休眠文件更改存储位置(3825)
- 3.各大搜索网站网站收录提交入口地址(3478)
- 4.ECharts仪表盘实例及参数使用详解(3431)
- 5.windows 10安装myeclipse 10破解补丁cracker.jar、run.bat闪退解决办法(3422)
- 6.HTML5 WebSocket与C#建立Socket连接实现代码(3179)
- 7.华为鸿蒙系统清除微信浏览器缓存方法(3171)
- 8.CERT_HAS_EXPIRED错误如何解决(2963)
- 9.Js异步async、await关键字详细介绍(lambda表达式中使用async和await关键字)(2599)
- 10.HBuilder编辑器格式化代码(2393)
