C# Task which returns a value

后端 未结 2 1839
既然无缘
既然无缘 2021-01-18 08:30

I\'m trying to run a function in a task but I\'m doing something wrong. Heres an example:

var t = Task.Factory.StartNew(() => GenerateResult(2)         


        
相关标签:
2条回答
  • 2021-01-18 08:35

    You are printing the task object that you created. For result, see .Result property:

    Console.WriteLine(t.Result);

    0 讨论(0)
  • 2021-01-18 08:47

    You need to use t.Result.

    For example

    Console.WriteLine(t.t.Result);
    

    Your code essentially looks like this:

    Task<int> t = Task<int>.Factory.StartNew(() => GenerateResult(2));
    

    And when you write Console.WriteLine(t); you are actually just printing the Task and not the integer. To be able to access the result you need to add .Result.

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