Michael Ray Lovett
Michael Ray Lovett

Reputation: 7050

How to start a task that takes a parameter and returns a value?

I'm trying to launch a task in C# that both takes a parameter and returns a value, but I can't seem to get the syntax right.

Here's as close as I have gotten: here's a task that is expected to return an int. I'm my lambda, I'm also showing it taking a single parameter, o:

Task<int> task1 = Task.Factory.StartNew<int>((o) => { return 2 ; }, 3);
Console.WriteLine(task1.Result);  // prints 2

The above line works (it returns a hardcoded value of 2, but you can see it's doing nothing with the parameter o, making it useless. If I do something with the parameter o, like this:

Task<int> task1 = Task.Factory.StartNew<int>((o) => { return (2 * o) ; }, 3);

I get a syntax message that Delegate 'System.Func' does not take 1 arguments.

Any help on how to achieve both things (pass a parameter and retrieve a value) from a task would be great!

Upvotes: 3

Views: 10676

Answers (3)

Seth Flowers
Seth Flowers

Reputation: 9190

o is the object state, and in your case, is the value you are passing in, or 3. You can cast it to an int.

Task<int> task = Task.Factory.StartNew<int>(o => {
    return 2 * (int)o;
}, 3);

Console.WriteLine(task.Result); // prints 6

See msdn's documentation on TaskFactory.StartNew which states:

state

Type: System.Object

An object containing data to be used by the function delegate.

Upvotes: 3

Nick Butler
Nick Butler

Reputation: 24383

The input ( state ) parameter for a Task can only be of type object, so it's actually not type safe.

The generic type parameter on Task<T> is the return type of the Task.

The best option is to use a closure:

int i = 3;
Task<int> task1 = Task.Factory.StartNew( () => 2 * i );

Upvotes: 3

YavgenyP
YavgenyP

Reputation: 2123

Theres Task<t> you can use (look here) T is the return value, of course. As of the parameter - you can just use ur variables within the annonymous delegate, so if you have the int o defined outside the task, you can just use it within the tasks annonymous delegate scope. you can see a sample here

Upvotes: 0

Related Questions