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

查看:1733
本文介绍了Task.Run()和await Task.Run()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序是使用常规Task.Run()并使用async和await(异步)设计的.在这两种情况下,都会从线程池中提取不同的线程来执行新任务.那么区别是什么呢?异步意味着它应该使用主线程并释放它,直到任务完成.但这也使用了另一个线程而不是主线程.

Following program is designed using general Task.Run() and using async and await (asynchronous). 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);
    }
}

//和异步

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);
            });
    }
}

推荐答案

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

What is the difference between Task.Run() and 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:

  • 雇人修剪草坪.
  • 告诉你的配偶修剪草坪.
  • 去观看Netflix.

您的第二个程序是:

  • 雇人修剪草坪.
  • 修剪草坪时观看Netflix.
  • 修剪完草坪并且电影结束后,告诉配偶修剪草坪.

很明显,这些是非常不同的工作流程.两者都是异步的,但是只有后者中有一个异步等待.我们异步等待告诉配偶,草坪被修剪了,直到草坪被修剪了.

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.

这篇关于Task.Run()和await Task.Run()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆