How to write an “awaitable” method?

后端 未结 6 1887
南笙
南笙 2020-12-07 13:20

I\'m finally looking into the async & await keywords, which I kind of "get", but all the examples I\'ve seen call async methods in the .Net framework, e.g. thi

6条回答
  •  鱼传尺愫
    2020-12-07 13:36

    Just convert your method to Task. Like @Romiox I usually use this extention:

    public static partial class Ext
    {
        #region Public Methods
        public static Task ToTask(Action action)
        {
            return Task.Run(action);
        }
        public static Task ToTask(Func function)
        {
            return Task.Run(function);
        }
        public static async Task ToTaskAsync(Action action)
        {
            return await Task.Run(action);
        }
        public static async Task ToTaskAsync(Func function)
        {
            return await Task.Run(function);
        }
        #endregion Public Methods
    }
    

    Now let we say you have

    void foo1()...
    
    void foo2(int i1)...
    
    int foo3()...
    
    int foo4(int i1)...
    

    ...

    Then you can declare your[async Method] like @Romiox

    async Task foo1Async()
    {
        return await Ext.ToTask(() => foo1());
    }
    async Task foo2Async(int i1)
    {
        return await Ext.ToTask(() => foo2(i1));
    }
    async Task foo3Async()
    {
        return await Ext.ToTask(() => foo3());
    }
    async Task foo4Async(int i1)
    {
        return await Ext.ToTask(() => foo4(i1));
    }
    

    OR

    async Task foo1Async()
    {
        return await Ext.ToTaskAsync(() => foo1());
    }
    async Task foo2Async(int i1)
    {
        return await Ext.ToTaskAsync(() => foo2(i1));
    }
    async Task foo3Async()
    {
        return await Ext.ToTaskAsync(() => foo3());
    }
    async Task foo4Async(int i1)
    {
        return await Ext.ToTaskAsync(() => foo4(i1));
    }
    

    ...

    Now you can use async and await for any of the fooAsync methods e.g. foo4Async

    async Task TestAsync () {
        ///Initial Code
        int m = 3;
        ///Call the task
        var X = foo4Async(m);
        ///Between
        ///Do something while waiting comes here
        ///..
        var Result = await X;
        ///Final
        ///Some Code here
        return Result;
    }
    

提交回复
热议问题