标签:方法体 5.0 article OLE 会同 ISE tps tin 获取
async修改一个方法,表示其为异步方法。而await表示等待一个异步任务的执行。js方面,在es7中开始得以支持;而.net在c#5.0开始支持。本文章将分别简单介绍他们在js和.net中的基本用法。
js中的异步,还是基于Promise实现的。没有Promise就办法谈异步了。并且await只能出现async修改的方法中;以及reject会触发catch(异常)。
class AsyncTest{ //simple example async run(){ //按照顺序等待后输出 let one = await this.output("one", 1000); console.log(‘output:‘ + one); let two = await this.output("two", 3000); console.log(two); console.log(‘run.....‘); } //await and Promise.all difference async runDiff(){ let one = this.output(‘diff one‘, 2000); let two = this.output(‘diff two‘, 2000); console.log( await two + await one ); //在2秒之后,两个都输出了,而不是各自都等待两秒 console.log(‘runDiff.....‘); } //Promise.all realize runAll(){ let nowTime = new Date(); console.log(‘b:‘ + nowTime.toTimeString()); let array = ["a", "b", "c"]; let that = this; array.forEach(async function(item){ console.log( await that.output(item, 2000) );//2秒后同时输出 }); let fn = async ()=>{ for(let item of array){ let v = await this.output(item, 2000); console.log(v ); //分步骤两秒执行 } } fn.call(this); } premosFn(){ let nowTime = new Date(); console.log(‘b:‘ + nowTime.toTimeString()); let array = ["a", "b", "c"]; let that = this; //promise.all let preFn = async function(){ let promises = array.map(function(item){ return that.output(item,2000); //同时开启多个定时器 }); let r = await Promise.all(promises); console.log(r.join(‘,‘)); } preFn(); } reject(){ let rejectFn = function(){ return new Promise((resolve, reject)=>{ setTimeout(()=>{ reject(); },2000); }); } let asyncReject = async function(){ try{ await rejectFn(); }catch( e) { console.log(‘reject.....‘); } } asyncReject(); } output(log, time){ return new Promise(resolve=>{ setTimeout(()=>{ var nowTime = new Date(); resolve( nowTime.toTimeString() + ":" + log + "\r\n"); }, time); }); } }
方法说明如下:
C#中异常是通过Task来实现的,所以标记了async的方法,其方法体中都可以出现await,否则不可以。以及Task中抛出的异常,如果没有同步等待,则不能获取异常
public class AsyncDemo { private Task<string> Output(string val, int time) { return System.Threading.Tasks.Task.Run(() => { System.Threading.Thread.Sleep(time * 1000); return (DateTime.Now.ToLongTimeString()) + ": " + val + "\r\n"; }); } public async System.Threading.Tasks.Task Run() { string oneVal = await Output("One", 2); string twoVal = await Output("Two", 2); System.Console.WriteLine("Run \r\n" + oneVal + " " + twoVal); } public async System.Threading.Tasks.Task RunDiff() { Task<string> oneTask = Output("one", 2); Task<string> twoTask = Output("two", 2); string val = await oneTask + await twoTask; System.Console.WriteLine("RunDiff \r\n" + val); } public async System.Threading.Tasks.Task RunAll() { System.Console.WriteLine("b:" + (DateTime.Now.ToLongTimeString())); string[] array = new string[3] { "a", "b", "c" }; foreach(var item in array) { string v = await Output(item, 2); System.Console.WriteLine(v); } } public async System.Threading.Tasks.Task PromiseFn() { System.Console.WriteLine("b:" + (DateTime.Now.ToLongTimeString())); string[] array = new string[3] { "a", "b", "c" }; List<System.Threading.Tasks.Task<string>> tasks = new List<System.Threading.Tasks.Task<string>>(); foreach (var item in array) { tasks.Add(Output(item, 2)); } //waitAll返回值不能获取,他返回为void,而WhenAll则返回为一个Task(这个Task就有其列表值) string[] r = await System.Threading.Tasks.Task.WhenAll(tasks.ToArray()); System.Console.WriteLine(string.Join(",",r)); } public async System.Threading.Tasks.Task Reject() { Func<System.Threading.Tasks.Task> func = async () => { throw new Exception("custom..."); await Output("reject", 2); }; await func(); } }
调用代码如下:
AsyncDemo asyncDemo = new AsyncDemo(); asyncDemo.Run().Wait(); asyncDemo.RunDiff().Wait(); asyncDemo.RunAll().Wait(); asyncDemo.PromiseFn().Wait(); try { asyncDemo.Reject().Wait(); }catch(Exception e) { System.Console.WriteLine("reject ex"); }
上述代码就是Js的async和await在c#中的翻版实现。 其中每个异步方法的调用,都用到了Wait方法来进行同步等待。以获取到结果。而没有像Js中那么难以控制。尤其注意,async方法中异常的捕获。
System.Console.WriteLine("b:" + (DateTime.Now.ToLongTimeString())); string[] array = new string[3] { "a", "b", "c" }; var r = await this.Output(array.First(), 2).ContinueWith((tsc) => { string v = tsc.GetAwaiter().GetResult(); return this.Output(v + "02", 2); }); System.Console.WriteLine(r.Result);
************转载:https://cloud.tencent.com/developer/article/1021822
标签:方法体 5.0 article OLE 会同 ISE tps tin 获取
原文地址:https://www.cnblogs.com/linybo/p/10091114.html