Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Run and Func<>

How can I run a Task that return value and takes a parameter? I see that there is an overloaded method Task.Run<TResult>(Func<TResult>) but how I can pass a parameter there?

like image 539
zavolokas Avatar asked Oct 29 '12 19:10

zavolokas


People also ask

What is Task <> C#?

A task is an object that represents some work that should be done. The task can tell you if the work is completed and if the operation returns a result, the task gives you the result.

What does Task run () do?

Run(Action) Queues the specified work to run on the thread pool and returns a Task object that represents that work.

What does calling Task ContinueWith () do?

ContinueWith(Action<Task,Object>, Object, TaskScheduler)Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes.

What is the difference between Task run and Task factory StartNew?

Task. Run(action) internally uses the default TaskScheduler , which means it always offloads a task to the thread pool. StartNew(action) , on the other hand, uses the scheduler of the current thread which may not use thread pool at all!


2 Answers

Func<TResult> doesn't take a parameter. Typically you would capture the parameter using a lambda expression instead. For example:

public void DoSomething(string text)
{
    Task<int> task = Task.Run(() => text.Length);
    ...
}

Here text is a captured variable... so even though you're just creating a Func<int>, it's using the method parameter.

like image 117
Jon Skeet Avatar answered Sep 21 '22 02:09

Jon Skeet


You could use the Task.Factory.StartNew() overloads to pass in a "state" object that holds all the parameters you want to you use. Here's a very basic example passing in a NameValueCollection, but you could obviously pass in any type of object you wanted.

Task<bool>.Factory.StartNew(
    ( a ) => {
        NameValueCollection nvc = a as NameValueCollection;
        if( nvc != null ) {
            nvc.AllKeys.ForEach( k => Console.WriteLine( nvc[k] ) );
        }
        return true;
    },
    new NameValueCollection() { { "param1", "hithere!" } } );
like image 30
Mike Parkhill Avatar answered Sep 18 '22 02:09

Mike Parkhill