Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Task which returns a value

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

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

static int GenerateResult(int i)
{ 
return i; 
}

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

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

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

like image 808
krtek Avatar asked Aug 02 '11 21:08

krtek


2 Answers

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

Console.WriteLine(t.Result);

like image 90
Marcin Deptuła Avatar answered Sep 20 '22 12:09

Marcin Deptuła


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.

like image 30
eandersson Avatar answered Sep 24 '22 12:09

eandersson