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

10,040

Solution 1

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 );

Solution 2

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.

Share:
10,040
Michael Ray Lovett
Author by

Michael Ray Lovett

Updated on June 04, 2022

Comments

  • Michael Ray Lovett
    Michael Ray Lovett almost 2 years

    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!