为什么不能使用Task<> .Result属性?

编程入门 行业动态 更新时间:2024-10-25 04:15:00
本文介绍了为什么不能使用Task<> .Result属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的任务有问题.当我尝试从任务中获取返回的变量时,无法使用.Result属性来获取它.这是我的代码:

I have a problem with my tasks. When I try to recive returned variable from my task I can't use a .Result property to get it. Here is my code:

var nextElement = dir.GetValue(i++).ToString(); Task buffering = Task<byte[]>.Run(() => imageHashing(nextElement)); bitmapBuffer = buffering.Result;

和imageHasing函数的声明如下: public bool [] imageHashing(字符串路径)

and imageHasing function is declared like this:public bool[] imageHashing(string path)

我收到一个错误提示:

严重性代码描述项目文件行抑制状态错误CS1061任务"不包含结果"的定义,并且没有扩展方法结果"接受类型为任务"的第一个参数可以找到(您是否缺少using指令或程序集参考?)

Severity Code Description Project File Line Suppression State Error CS1061 'Task' does not contain a definition for 'Result' and no extension method 'Result' accepting a first argument of type 'Task' could be found (are you missing a using directive or an assembly reference?)

来自此Microsoft网站有效,我不明白为什么.

Example from this microsoft website works, and I can't understand why.

推荐答案

正如其他人所述,编译器错误在变量声明中( Task 没有 Result 属性):

As others have noted, the compiler error is in your variable declaration (Task does not have a Result property):

var nextElement = dir.GetValue(i++).ToString(); var buffering = Task.Run(() => imageHashing(nextElement)); bitmapBuffer = buffering.Result;

但是,此代码也有问题.特别是,如果您只是要阻塞当前线程直到完成,则将工作踢到后台线程是没有意义的.您也可以直接调用该方法:

However, this code is also problematic. In particular, it makes no sense to kick work off to a background thread if you're just going to block the current thread until it completes. You may as well just call the method directly:

var nextElement = dir.GetValue(i++).ToString(); bitmapBuffer = imageHashing(nextElement);

或者,如果您在UI线程上并且不想阻止UI,则使用 await 而不是 Result :

Or, if you are on a UI thread and do not want to block the UI, then use await instead of Result:

var nextElement = dir.GetValue(i++).ToString(); bitmapBuffer = await Task.Run(() => imageHashing(nextElement));

更多推荐

为什么不能使用Task&lt;&gt; .Result属性?

本文发布于:2023-11-16 09:40:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1603126.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   amp   Task   lt   Result

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!