Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

c# - Why can't use Task<>.Result property?

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;

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

I get an error saing:

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?)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...