MFatihMAR MFatihMAR - 1 month ago 9
C# Question

Task.Run with Parameter(s)?

I'm working on a multi-tasking network project and I'm new on

Threading.Tasks
. I implemented a simple
Task.Factory.StartNew()
and I wonder how can I do it with
Task.Run()
?

Here is the basic code:

Task.Factory.StartNew(new Action<object>(
(x) =>
{
// Do something with 'x'
}), rawData);


I looked into
System.Threading.Tasks.Task
in Object Browser and I couldn't find a
Action<T>
like parameter. There is only
Action
that takes
void
parameter and no type.

There are only 2 things similiar:
static Task Run(Action action)
and
static Task Run(Func<Task> function)
but can't post parameter(s) with both.

Yes, I know I can create a simple extension method for it but my main question is can we write it on single line with
Task.Run()
?

Answer
private void RunAsync()
{
    string param = "Hi";
    Task.Run(() => MethodWithParameter(param));
}

private void MethodWithParameter(string param)
{
    //Do stuff
}
Comments