简体   繁体   English

Task.Run()和await Task.Run()有什么区别?

[英]What is the difference between Task.Run() and await Task.Run()?

Following program is designed using general Task.Run() and using async and await (asynchronous). 以下程序使用通用Task.Run()并使用async和await(异步)设计。 In both cases a different Thread is taken from Thread pool for new task. 在这两种情况下,从线程池中获取不同的线程以用于新任务。 So, what is the difference? 那么区别是什么呢? Asynchronous means it should use the main thread and free it until task completed. 异步意味着它应该使用主线程并释放它直到任务完成。 But it is also using another thread rather than using main thread. 但它也使用另一个线程而不是使用主线程。

public class Worker2
{
    public bool IsComplete { get; private set; }
    internal void DoWork()
    {
        this.IsComplete = false;
        Console.WriteLine("Doing Work.");
        Task.Run(new Action(LongOperation));
        Console.WriteLine("Work Completed");
        IsComplete = true;
    }

    private void LongOperation()
    {
            Console.WriteLine("long operation thread thread :" + Thread.CurrentThread.ManagedThreadId);//Thread Id = 7. it is different from main thread id.
            Console.WriteLine("Working!");
            Thread.Sleep(3000);
    }
}

//And asynchronous //和异步

public class Worker2
{
    public bool IsComplete { get; private set; }
    internal async void DoWork()
    {
        this.IsComplete = false;
        Console.WriteLine("Doing Work.");       
        await LongOperation();
        Console.WriteLine("Work Completed");
        IsComplete = true;
    }

    private Task LongOperation()
    {

        return Task.Run(() =>
            {
                Console.WriteLine("long operation thread thread :" + Thread.CurrentThread.ManagedThreadId);
                Console.WriteLine("Working!");
                Thread.Sleep(3000);
            });
    }
}

What is the difference between Task.Run() and await Task.Run()? Task.Run()和await Task.Run()有什么区别?

The first starts a task and then does the work immediately after that task, before the task completes . 第一个启动任务, 然后在任务完成之前立即完成该任务

The second starts a task and then does different work until the task is completed, at which point it does the work after the task. 第二个启动一个任务,然后完成不同的工作,直到任务完成,此时它完成任务后的工作。

Let's make an analogy. 我们来做个比喻吧。 Your first program is like doing this: 你的第一个程序就像这样做:

  • Hire someone to mow the lawn. 雇人去割草坪。
  • Tell your spouse the lawn is mowed. 告诉你的配偶修剪草坪。
  • Go watch Netflix. 去看Netflix。

Your second program is: 你的第二个项目是:

  • Hire someone to mow the lawn. 雇人去割草坪。
  • Watch Netflix while the lawn is being mowed. 在修剪草坪时观看Netflix。
  • When the lawn is done being mowed and the movie is over, tell spouse the lawn is mowed. 草坪完成修剪并且电影结束后,告诉配偶修剪草坪。

Clearly those are very different workflows. 显然,这些是非常不同的工作流程。 Both are asynchronous, but only the latter has an asynchronous wait in it. 两者都是异步的,但只有后者才有异步等待 We asynchronously wait to tell the spouse that the lawn is mowed until it actually is mowed . 我们异步地等待告诉配偶草坪被修剪, 直到它实际被修剪

You misunderstood what asynchronous code means. 你误解了异步代码的含义。 Whenever you call any function which passes( delegates ) the actual code execution to some other entity(other dedicated thread, thread pool, etc.) and the function immediately returns you have an asynchronous call. 无论何时调用任何将实际代码执行( 委托 )传递给其他实体(其他专用线程,线程池等)的函数,函数会立即返回,您将进行异步调用。 An asynchronous call is the antipode to a blocking call. 异步调用是阻塞调用的对象。

In C# there are a few method to write an asynchronous code and await / async just make writing simpler. 在C#中有一些编写异步代码的方法和await / async只是使编写更简单。 It adds nothing in terms of functional to the language. 它在语言功能方面没有增加任何内容。 It is just syntactic sugar to make programs easier to write by providing a way to write asynchronous code in the same style we write blocking code. 通过提供一种以我们编写阻塞代码的相同样式编写异步代码的方法,使程序更容易编写只是语法糖。

That being said, Task.Run(new Action(LongOperation)); 话虽这么说, Task.Run(new Action(LongOperation)); is an asynchronous call as well as LongOperation() from your second snippet. 是第二个代码片段中的异步调用以及LongOperation() The difference between them, is that in the first example, when Task.Run returns the code which immediately follows that line gets executed immediately(provided no thread switch happened). 它们之间的区别在于,在第一个示例中,当Task.Run返回紧跟在该行之后立即执行的代码时(如果没有发生线程切换)。 And in the second example the lines which follow await get executed only when LongOperation completed on some thread provided by the thread pool( DoWork immediately returns when it encounters await ). 在第二个例子中,只有在线程池提供的某个线程上完成LongOperationLongOperation执行await LongOperation的行( DoWork在遇到await时立即返回)。

I recommend you to read more about TPL and async / await . 我建议你阅读更多关于TPLasync / await There are plenty blog posts out there about both, not to mention great books covering all these features in details. 关于这两者的博客文章很多,更不用说详细介绍了所有这些功能的精彩书籍。

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

相关问题 "await Task.Run(); return;" 之间的任何区别和“返回 Task.Run()”? - Any difference between "await Task.Run(); return;" and "return Task.Run()"? Task.Run和Task.Factory.StartNew有什么区别 - What is the difference between Task.Run and Task.Factory.StartNew Task.Run() 和 Task.Factory.StartNew() 有什么区别 - What is the difference between Task.Run() and Task.Factory.StartNew() 在 Blazor 中,`await Task.Run(StateHasChanged)` 和 `await InvokeAsync(StateHasChanged)` 有什么区别? - In Blazor what is the difference between `await Task.Run(StateHasChanged)` and `await InvokeAsync(StateHasChanged)`? await XXAsync()和await Task.Run(()=> {XX()}之间的实际区别是什么 - What's The Actual Difference Between await XXAsync() And await Task.Run(()=>{XX() } Task.Run(()MethodName())并等待Task.Run(async()=> MethodName()) - Task.Run( () MethodName()) and await Task.Run(async () => MethodName()) 丢弃 DoAwait() VS Task.Run(() => DoAwait()) 有什么区别 - What is the difference between discarding DoAwait() VS Task.Run(() => DoAwait()) 调用等待使用Task.Run()创建的任务 - Calling await on a task created with Task.Run() 等待 Task.Run 与等待 - await Task.Run vs await 到Task.Run或不到Task.Run - To Task.Run or not to Task.Run
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM