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?
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.
Run(Action) Queues the specified work to run on the thread pool and returns a Task object that represents that work.
ContinueWith(Action<Task,Object>, Object, TaskScheduler)Creates a continuation that receives caller-supplied state information and executes asynchronously when the target Task completes.
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!
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.
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!" } } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With