简体   繁体   English

可以一个任务<tresult>用于启动和存储异步方法,而无需显式调用 Run 或 StartNew 的 Task 方法?</tresult>

[英]Can a Task<TResult> be used to start and store a async method without an explicit Task method call to Run or StartNew?

When I look at this example from the MS docs, the call a Task without using Run or StartNew like this,当我从 MS 文档中查看此示例时,调用Task而不使用RunStartNew像这样,

Coffee cup = PourCoffee();
Console.WriteLine("Coffee is ready");

Task<Egg> eggsTask = FryEggsAsync(2);
Task<Bacon> baconTask = FryBaconAsync(3);
Task<Toast> toastTask = ToastBreadAsync(2);

Toast toast = await toastTask;
ApplyButter(toast);
ApplyJam(toast);
Console.WriteLine("Toast is ready");
Juice oj = PourOJ();
Console.WriteLine("Oj is ready");

Egg eggs = await eggsTask;
Console.WriteLine("Eggs are ready");
Bacon bacon = await baconTask;
Console.WriteLine("Bacon is ready");

Console.WriteLine("Breakfast is ready!");

But all the documentation I have found looks like you have to call Run , StartNew , or something else.但是我发现的所有文档看起来你必须调用RunStartNew或其他东西。

The article that has the Breakfast example says,有早餐例子的文章说,

You start a task and hold on to the Task object that represents the work.您开始一项任务并坚持代表该工作的任务 object。 You'll await each task before working with its result.在处理其结果之前,您将等待每个任务。

Why don't they have to call Run or StartNew or some other method?为什么他们不必调用 Run 或 StartNew 或其他方法?

Here is the complete working part I have.这是我拥有的完整工作部分。 It runs, and I understand what it accomplishes, but I don't know why they don't use Run (()=> , etc.它运行,我理解它完成了什么,但我不知道他们为什么不使用Run (()=>等。

 namespace AsyncBreakfast
    {
        // These classes are intentionally empty for the purpose of this example.
        // They are simply marker classes for the purpose of demonstration,
        // contain no properties, and serve no other purpose.
        internal class Bacon { }
        internal class Coffee { }
        internal class Egg { }
        internal class Juice { }
        internal class Toast { }

        class Program
        {
            static async Task Main(string[] args)
            {
                Coffee cup = PourCoffee();
                Console.WriteLine("Coffee is ready");

                Task<Egg> eggsTask = FryEggsAsync(2);
                Task<Bacon> baconTask = FryBaconAsync(3);
                Task<Toast> toastTask = ToastBreadAsync(2);

                Toast toast = await toastTask;
                ApplyButter(toast);
                ApplyJam(toast);
                Console.WriteLine("Toast is ready");
                Juice oj = PourOJ();
                Console.WriteLine("Oj is ready");

                Egg eggs = await eggsTask;
                Console.WriteLine("Eggs are ready");
                Bacon bacon = await baconTask;
                Console.WriteLine("Bacon is ready");

                Console.WriteLine("Breakfast is ready!");

            }

        static async Task<Toast> MakeToastWithButterAndJamAsync(int number)
        {
            var toast = await ToastBreadAsync(number);
            ApplyButter(toast);
            ApplyJam(toast);

            return toast;
        }

        private static Juice PourOJ()
        {
            Console.WriteLine("Pouring orange juice");
            return new Juice();
        }

        private static void ApplyJam(Toast toast) =>
            Console.WriteLine("Putting jam on the toast");

        private static void ApplyButter(Toast toast) =>
            Console.WriteLine("Putting butter on the toast");

        private static async Task<Toast> ToastBreadAsync(int slices)
        {
            for (int slice = 0; slice < slices; slice++)
            {
                Console.WriteLine("Putting a slice of bread in the toaster");
            }
            Console.WriteLine("Start toasting...");
            await Task.Delay(3000);
            Console.WriteLine("Remove toast from toaster");

            return new Toast();
        }

        private static async Task<Bacon> FryBaconAsync(int slices)
        {
            Console.WriteLine($"putting {slices} slices of bacon in the pan");
            Console.WriteLine("cooking first side of bacon...");
            await Task.Delay(3000);
            for (int slice = 0; slice < slices; slice++)
            {
                Console.WriteLine("flipping a slice of bacon");
            }
            Console.WriteLine("cooking the second side of bacon...");
            await Task.Delay(3000);
            Console.WriteLine("Put bacon on plate");

            return new Bacon();
        }

        private static async Task<Egg> FryEggsAsync(int howMany)
        {
            Console.WriteLine("Warming the egg pan...");
            await Task.Delay(3000);
            Console.WriteLine($"cracking {howMany} eggs");
            Console.WriteLine("cooking the eggs ...");
            await Task.Delay(3000);
            Console.WriteLine("Put eggs on plate");

            return new Egg();
        }

        private static Coffee PourCoffee()
        {
            Console.WriteLine("Pouring coffee");
            return new Coffee();
        }
    }

Why don't they have to call Run or StartNew or some other method?为什么他们不必调用 Run 或 StartNew 或其他方法?

By convention , Tasks are returned "hot"; 按照惯例,任务返回“热”; ie, already in progress.即,已经在进行中。

Task.Run will schedule the asynchronous method onto a thread pool thread. Task.Run将异步方法调度到线程池线程上。 Just calling the method directly will begin executing the asynchronous method on the current thread (as I explain on my blog).直接调用该方法将开始在当前线程上执行异步方法(正如我在博客中解释的那样)。

Regarding the "most common" phrase: that was likely true when it was written over 12 years ago.关于“最常见”的短语:这在 12 年前写成时可能是正确的。 I'd say it's certainly not true today;我会说今天肯定不是真的。 the most common way to get tasks these days is by calling an async method.这些天来获取任务的最常见方法是调用async方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM