Await new Task( … ) : Task does not run?

前端 未结 4 2018
暖寄归人
暖寄归人 2021-01-02 02:20

A continuation of a question asked here :

In the aforementioned question I have the following function which returns an object of type Task (for incremental testing

4条回答
  •  执念已碎
    2021-01-02 02:44

    OK, I think I've figured this out. Please examine this code:

    class Program
    {
        public static void Main(string[] args)
        {
            // Only RUN the task as needed.  FooGet 
            // still allows you to generalize your task.
            Task.Run(() =>
            {
                dynamic value = FooGet();
    
                value.RunSynchronously();
    
                Console.WriteLine(value.Result.Result.ToString());
            });
    
            while (true) Thread.Sleep(100);
        }
    
        private static Task FooGet()
        {
            var task = new Task(() => {
                return asyncBar();
            });
    
            return task;
        }
    
        private async static Task asyncBar()
        {
            // do work!
            return "Hello, world!";
        }
    }
    
        

    提交回复
    热议问题