我的任务有问题.当我尝试从任务中获取返回的变量时,无法使用.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<> .Result属性?
发布评论