在调用 Wait 之前访问任务上的结果实际上有什么作用? [英] What does accessing a Result on a Task before calling Wait actually do?

查看:38
本文介绍了在调用 Wait 之前访问任务上的结果实际上有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var task = Task.Run(() => DoSomeStuff()).Result;

幕后发生了什么?

我做了一个小测试:

using System;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {
        var r = Task.Run( () => {Thread.Sleep(5000); return 123; }).Result;
        Console.WriteLine(r);
    }
}

它在 5 秒后打印123".那么访问 Task 上的任何此类属性是否可以作为调用 Task.Wait() 的快捷方式,即这样做是否安全?

It prints "123" after 5s. So does accessing any such property on Task act as a shortcut to calling Task.Wait() i.e. is this safe to do?

以前我的代码称为 Task.Delay(5000),它立即返回123".我在我的问题中解决了这个问题,但将其留在这里作为评论和答案参考.

Previously my code called Task.Delay(5000) which returned "123" immediately. I fixed this in my question but leave this here as comments and answers reference it.

推荐答案

那么访问 Task 上的任何此类属性是否可以作为调用 Task.Wait() 的快捷方式?

So does accessing any such property on Task act as a shortcut to calling Task.Wait()?

是的.

来自 文档:

访问[Result]属性的get访问器会阻塞调用线程,直到异步操作完成;它相当于调用 等待 方法.

Accessing the [Result] property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method.

然而,您的测试并没有像您想象的那样做.

However, your test doesn't do what you think it does.

Task.Delay(..) 返回一个在指定时间后完成的 Task.它不会阻塞调用线程.

Task.Delay(..) returns a Task which completes after the specified amount of time. It doesn't block the calling thread.

所以 () =>{ Task.Delay(5000);返回 123;} 只需创建一个新的Task(将在5 秒内完成),然后将其丢弃并立即返回123.

So () => { Task.Delay(5000); return 123; } simply creates a new Task (which will complete in 5 seconds), then throws it away and immediately returns 123.

您可以:

  1. 通过执行 Task.Delay(5000).Wait()(与 Thread.Sleep(5000) 做同样的事情)阻止调用线程立>
  2. 异步等待Task.Delay返回的Task完成:Task.Run(async() => { await Task.Delay(5000); 返回 123; })
  1. Block the calling thread, by doing Task.Delay(5000).Wait() (which does the same thing as Thread.Sleep(5000))
  2. Asynchronously wait for the Task returned from Task.Delay to complete: Task.Run(async () => { await Task.Delay(5000); return 123; })

这篇关于在调用 Wait 之前访问任务上的结果实际上有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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