简体   繁体   English

Task.Run在异步和等待中的作用

[英]Role of Task.Run in async and await

I have got a simple program for async and await: 我有一个用于异步和等待的简单程序:

class Program
    {
        static void Main()
        {
           var demo = new AsyncAwaitDemo();
           Task.Run(() => {demo.DoStuff()};

           while (true)
           {
               Console.WriteLine("Doing Stuff on the Main Thread...................");
           }
        }
    }

    public class AsyncAwaitDemo
    {
        public async Task DoStuff()
        {
        await LongRunningOperation();

        }

        private static async Task<string> LongRunningOperation()
        {
            int counter;

            for (counter = 0; counter < 50000; counter++)
            {
                Console.WriteLine(counter);
            }

            return "Counter = " + counter;
        }
    }

My first question is : 我的第一个问题是:

  1. Is it mandatory to use Task.Run in any async and await method because I just removed and the program becomes synchronous.I am aware of the fact that await is used to create suspension points and doesnt get executed further until the awaited function completes for that thread. 是否必须在任何asyncawait方法中使用Task.Run ,因为我刚刚删除了该程序,并且该程序变得同步了。线。

Secondly, 其次,

  1. How many number of threads while the following of code creates? 下面的代码创建多少个线程?

    Task.Run(() => {demo.DoStuff()}; Task.Run(()=> {demo.DoStuff()};

    If it is more than one , then is the number of threads dependent on the inner operation , in this example it is for loop with counter . 如果大于1,则线程数是否取决于内部操作,在此示例中,它是带计数器的for循环。

I am beginning to understand the asynchronous programming in C# , read and practiced few samples . 我开始了解C#中的异步编程,阅读并练习了一些示例。 I am able to get the context almost apart from the clarifications I asked as above. 除了上述要求外,我几乎能够弄清上下文。

async / await has nothing to do with Task.Run ; async / awaitTask.Run没有Task.Run ; however, they do work well together in some scenarios. 但是,它们在某些情况下可以很好地协同工作。

Task.Run runs some code on a thread pool thread. Task.Run在线程池线程上运行一些代码。 async / await is a code transformation that allows you to write asynchronous code in a more natural, imperative manner (see my async intro for more details about how async works). async / await是一种代码转换,可让您以更自然,更必要的方式编写异步代码(有关async工作原理的更多详细信息,请参见我的async介绍 )。

Is it mandatory to use Task.Run in any async and await method because I just removed and the program becomes synchronous. 是否必须在任何异步和等待方法中使用Task.Run,​​因为我刚刚删除了该程序,因此程序变得同步了。

Not at all! 一点也不! async / await are very commonly used without Task.Run . async / await非常常见的没有Task.Run Anytime that you have a truly asynchronous operation, then you can use async / await . 只要您执行真正的异步操作,就可以使用async / await Generally speaking, anything I/O-based is a good example of a naturally asynchronous operation. 一般而言,任何基于I / O的方法都是自然异步操作的一个很好的例子。 So, you can use something like HttpClient.GetStringAsync using just async / await without any Task.Run at all. 因此,您可以仅使用async / await使用类似HttpClient.GetStringAsync东西,而无需任何Task.Run

Note, however, that it is almost always wrong to use async without await . 但是请注意,在没有await情况下使用async几乎总是错误的。 The compiler will give you a warning for LongRunningOperation , informing you of the fact that it's not actually asynchronous. 编译器会警告您LongRunningOperation ,并告知您它实际上不是异步的。

How many number of threads while the following of code creates? 下面的代码创建多少个线程? Task.Run(() => {demo.DoStuff()}; Task.Run(()=> {demo.DoStuff()};

That code just queues DoStuff to the thread pool. 该代码只是将DoStuff排队到线程池中。 A thread pool thread will execute DoStuff . 线程池线程将执行DoStuff Thread creation is dependent on a lot of other factors. 线程创建取决于许多其他因素。

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

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