2

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.

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
Jakub Gwiazda
  • 55
  • 1
  • 5
  • 6
    Well, good news, because your use of Task here is completely pointless. You're blocking the current thread, so you can just call imageHashing directly and skip Task.Run. –  Aug 11 '17 at 12:59
  • 3
    You need to declare it as `Task`. See [this question](https://stackoverflow.com/questions/11333297/threading-tasks-task-does-not-contain-a-definition-for-result) for explanation. – Tamás Szabó Aug 11 '17 at 12:59
  • Or use var instead – Matthew Steeples Aug 11 '17 at 13:01
  • 1
    I mean it's not totally pointless, it's adding the aditional overhead of spawning a thread pool thread and then using that, so it is making your code **a lot** less efficient – Liam Aug 11 '17 at 13:01

3 Answers3

3

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));
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
-2

You should declare buffering variable as Task<byte[]> buffering = Task<byte[]>.Run(() => imageHashing(nextElement));

-3

You should use Task<bool[]> for the buffering variable. Not specifying the type means that the operation is not expected to return any result.

Adrian P.
  • 1
  • 2