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

后端 未结 3 911
深忆病人
深忆病人 2020-12-12 07:05

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 nextEleme         


        
相关标签:
3条回答
  • 2020-12-12 07:27

    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));
    
    0 讨论(0)
  • 2020-12-12 07:31

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

    0 讨论(0)
  • 2020-12-12 07:41

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

    0 讨论(0)
提交回复
热议问题