async 和 await 之非同步程式設計的學習

小龍女先生發表於2018-01-07

      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的異常。

二、在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);

相關文章