使用 Task 和 Task<TResult> 有什么区别?在 C# 中 [英] What&#39;s the difference between using Task and Task&lt;TResult&gt; in C#

查看:82
本文介绍了使用 Task 和 Task<TResult> 有什么区别?在 C# 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些实验来理解 Tasks.这是我偶然发现的:

Hi I'm making some experiment to understand Tasks. Here what I stumbled upon:

static void Main(string[] args)
    {
        Console.WriteLine(String.Format("Master in the thread {0}", Thread.CurrentThread.ManagedThreadId));

        Task t1 = Task.Factory.StartNew(TaskDoNothing);
        Console.WriteLine(String.Format("Result before wait"));
        Task.WaitAll(t1);            
        Console.WriteLine(String.Format("Result after wait"));

        Console.ReadLine();
    }

    static void TaskDoNothing()
    {
        Console.WriteLine(String.Format("Task in the thread {0}", Thread.CurrentThread.ManagedThreadId));
        Thread.Sleep(3000);            
    }

这将按我的预期工作.等待前的结果立即显示,当任务完成时,我们看到等待后的结果".但是当我将其更改为使用 Task 时,执行的优先级似乎发生了变化:

This will work as I expected. The "Result before wait is shown right away and when the task is done, we see the "Result after wait". But when i change it to use Task<TResult>, the priority of execution seems changed:

static void Main(string[] args)
    {
        Console.WriteLine(String.Format("Master in the thread {0}", Thread.CurrentThread.ManagedThreadId));

        Task<int> t1 = Task<int>.Factory.StartNew(TaskDoNothing);
        Console.WriteLine(String.Format("Result before wait: {0}", t1.Result));
        Task.WaitAll(t1);            
        Console.WriteLine(String.Format("Result after wait: {0}", t1.Result));

        Console.ReadLine();
    }

    static int TaskDoNothing()
    {
        Console.WriteLine(String.Format("3- Task in the thread {0}", Thread.CurrentThread.ManagedThreadId));
        Thread.Sleep(3000);
        return 3;
    }

等待前的结果"仅在任务完成时与等待后的结果"一起显示.看起来整个任务在主线程恢复之前执行,即使 ManagedThreadId 告诉它们在单独的线程上.

The "Result before wait is only shown when the task is done along with the "Result after wait". It looks like the whole Task is executed before the main thread resumes even if the ManagedThreadId tells that they are on separate thread.

有人可以帮我吗?提前致谢!

Can someone help me with that? Thanks in advance!

推荐答案

Task.Result 是一个阻塞操作.事实上,你在等待任务完成.如果你想要结果而不是等待,那么你可以使用 ContinueWith

Task.Result is a blocking operation. In fact, you wait for the task to finish. If you want the result but not wait, then you can use ContinueWith

这篇关于使用 Task 和 Task<TResult> 有什么区别?在 C# 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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