Async和await关键字的用法
2016-03-01 15:01
876 查看
async & await 的前世今生(Updated)
1. 方法打上Async关键字, 就可以使用await调用别的Async方法了2. 记得在需要异步执行的方法里面调用await或者newstask, 才能开启新的线程
static void Main(string[] args) { // 异步方式 Console.WriteLine("\n异步方式测试开始!main线程id是{0}",System.Threading.Thread.CurrentThread.ManagedThreadId); AsyncMethod(0); //AsyncMethod_taks(10); Console.WriteLine("异步方式测试结束!"); Console.ReadKey(); } // 异步操作 private static async void AsyncMethod(int input) { Console.WriteLine("进入异步操作!线程id是{0}", System.Threading.Thread.CurrentThread.ManagedThreadId); var result = await AsyncWork(input); Console.WriteLine("最终结果{0}, 线程ID是{1}", result, System.Threading.Thread.CurrentThread.ManagedThreadId); Console.WriteLine("退出异步操作!"); } // 模拟耗时操作(异步方法) private static async Task<int> AsyncWork(int val) { await Task.Delay(2000); for (int i = 0; i < 5; ++i) { Console.WriteLine("耗时操作{0}, 线程id是 {1}", i, System.Threading.Thread.CurrentThread.ManagedThreadId); val++; } return val; }
更推荐这种写法
相关文章推荐
- 别再让C++头文件中出现“using namespace xxx;” http://blog.csdn.net/dj0379/article/details/11565387
- BIO,NIO,AIO的理解
- MQ:Communications link failure
- "FATAL: Module scsi_wait_scan not found" 解决方法
- SVN客户端解决authorization failed问题
- Leetcode ☞ 70. Climbing Stairs
- 为啥NSString的属性要用copy而不用retain
- 【POJ】1363 - Rails(栈)
- "File not found""linker command failed with exit code 1" in Xcode 7.2.1
- CSDN与JetBrains达成战略合作 开启软件商城新篇章
- 广度优先搜索算法 http://blog.csdn.net/ywjun0919/article/details/8838491
- 【转】解决svn Authorization failed错误
- 【杭电oj】1022 - Train Problem I(栈)
- JetBrains老用户转换全新订阅授权模式可享受6折优惠
- Mac Air 优势
- SonarQube EXECUTION FAILURE
- 马克扎克伯格谈未来科技趋势:视频、人工智能、VR
- 可失败构造器(Failable Initializers)
- 解析腾讯企业邮箱到自己域名,设置mail的cname
- Codeforces 628F Bear and Fair Set