意味着该为异步方法。表示其为异步方法。

     
async修改一个措施,表示该也异步方法。而await表示等一个异步任务之执行。js方面,在es7受开始好支持;而.net在c#5.0初始支持。本章将各自简单介绍他们以js和.net中的主导用法。

     
async修改一个智,表示该也异步方法。而await表示等一个异步任务的履行。js方面,在es7遇启好支持;而.net在c#5.0开支持。本章以分头简单介绍他们在js和.net中之主导用法。

一如既往、在js中的贯彻

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);
        });
    }
}

艺术求证如下:

  • output:简单的输出方法,但回到了一Promise。
  • run: 使用await来等待两涂鸦对output的行
  • runDiff:调用output时即创办promise。两个promise会同步执行
  • runAll:多任务并实施及遵循步骤执行的贯彻方式。也便是forEach和for方法体中行使await的分别
  • premosFn: promise.all的使用。
  • reject: promise的reject会触发await的异常。

同样、在js中之兑现

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);
        });
    }
}

术求证如下:

  • output:简单的出口方法,但回到了一Promise。
  • run: 使用await来等待两蹩脚对output的尽
  • runDiff:调用output时就创办promise。两只promise会同步施行
  • runAll:多任务并执行和遵循步骤执行之兑现方式。也不怕是forEach和for方法体中运用await的分别
  • premosFn: promise.all的使用。
  • reject: promise的reject会触发await的异常。

二、在c#丁之落实

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方法吃异常的捕获。

二、在c#蒙的贯彻

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方法吃十分的破获。

老三、两者的异同点

  • js中的async方法的调用,是从未wait方法来等结果的实践的,只能通过promise来监听执行结果
  • c#倍受之async方法,由于推荐返回Task或者Task<T>,所以可以据此Wait来等待执行结果,如果async方法返回吗void,则跟js类似。
    C#面临之底示例方法的调用者破获不了大:

    public async void Run()
    {
        string oneVal = await Output("One", 2);
        string twoVal = await Output("Two", 2);
        System.Console.WriteLine("Run" + oneVal + " " + twoVal);
    }
    
  • c#受到之Task可以异步方法的链式调用,即可将眼前一模一样职责之行结果作为次任务的参数传入,当然js的Promise也全然是足以好自在的实现:

    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);

老三、两者的异同点

  • js中的async方法的调用,是从未wait方法来等结果的实践的,只能通过promise来监听执行结果
  • c#饱受之async方法,由于推荐返回Task或者Task<T>,所以可以据此Wait来等待执行结果,如果async方法返回吗void,则与js类似。
    C#屡遭之脚示例方法的调用者破获不了酷:

    public async void Run()
    {
        string oneVal = await Output("One", 2);
        string twoVal = await Output("Two", 2);
        System.Console.WriteLine("Run" + oneVal + " " + twoVal);
    }
    
  • c#遭到之Task可以异步方法的链式调用,即可将前方一模一样职责的尽结果作次任务之参数传入,当然js的Promise也完全是足以生自在的落实:

    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);

相关文章