C # task returning value

I am trying to run a function in a task, but I am doing something wrong. Here is an example:

var t = Task<int>.Factory.StartNew(() => GenerateResult(2)); static int GenerateResult(int i) { return i; } 

At the end of Console.WriteLine(t); This returns:

System.Threading.Tasks.Task`1 [System.Int32]

I want me to be 2. What am I doing wrong here?: /

+6
source share
2 answers

You print the created task object. To get the result, see .Result Property:

Console.WriteLine(t.Result);

+13
source

You need to use t.Result .

for instance

 Console.WriteLine(ttResult); 

Your code looks something like this:

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

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

+6
source

Source: https://habr.com/ru/post/894147/


All Articles