How to run a method with arguments in a separate thread using Parallel tasks

here is a sample code for

private void MethodStarter()
{
Task myFirstTask = Task.Factory.StartNew(Method1);
Task mySecondTask = Task.Factory.StartNew(Method1);
}

private void Method1()
{
 // your code
}

private void Method2()
{
 // your code
}

I am looking for a code snippet for Parallel Tasks with which I can perform a callback and pass an argument to a function. can anyone help.

+5
source share
2 answers

If I understood your question correctly, it could be anwser:

private void MethodStarter()
{
    Task myFirstTask = Task.Factory.StartNew(() => Method1(5));
    Task mySecondTask = Task.Factory.StartNew(() => Method2("Hello"));
}

private void Method1(int someNumber)
{
     // your code
}

private void Method2(string someString)
{
     // your code
}

If you want to start all threads at once, you can use the example specified by h1ghfive.

UPDATE: An example with a callback that should work, but I have not tested it.

private void MethodStarter()
{
    Action<int> callback = (value) => Console.WriteLine(value);
    Task myFirstTask = Task.Factory.StartNew(() => Method1(5, callback));
    Task mySecondTask = Task.Factory.StartNew(() => Method2("Hello"));
}

private void Method1(int someNumber, Action<int> intCallback)
{
     // your code
     intCallback(100); // will call the call back function with the value of 100
}

private void Method2(string someString)
{
     // your code
}

You can view Continuation if you do not want to pass callback functions.

+12
source

- :

Parrallel.Invoke(
  () => Method1(yourString1),
  () => Method2(youString2));
+3

All Articles