Chaining two functions () -> Task and A->Task

前端 未结 4 1609
你的背包
你的背包 2021-02-08 13:33

I don\'t know if I am thinking in the wrong way about TPL, but I have difficulty understanding how to obtain the following:

I have two functions

Task<         


        
4条回答
  •  终归单人心
    2021-02-08 13:50

    In case you are familiar with LINQ (and the Monad concept behind it), then below is a simple Task monad which will allow you to compose the Tasks.

    Monad implementation:

    public static class TaskMonad
        {
            public static Task ToTask(this T t)
            {
                return new Task(() => t);
            }
    
            public static Task SelectMany(this Task task, Func> f)
            {
                return new Task(() =>
                {
                    task.Start();
                    var t = task.Result;
                    var ut = f(t);
                    ut.Start();
                    return ut.Result;
                });
            }
    
            public static Task SelectMany(this Task task, Func> f, Func c)
            {
                return new Task(() =>
                {
                    task.Start();
                    var t = task.Result;
                    var ut = f(t);
                    ut.Start();
                    var utr = ut.Result;
                    return c(t, utr);
                });            
            }
        }
    

    Usage example:

            public static void Main(string[] arg)
            {
                var result = from a in getA()
                             from b in getB(a)
                             select b;
                result.Start();
                Console.Write(result.Result);
            }
    

提交回复
热议问题