Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run method with arguments in separate thread using Parallel Tasks

here is sample of 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 code snippet for Parallel Tasks by which i can do the callback and pass argument to function also. can anyone help.

like image 472
Thomas Avatar asked Aug 13 '12 08:08

Thomas


1 Answers

If I understood your question right this might be the 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 the threads at the same time you can use the example given by h1ghfive.

UPDATE: An example with callback that should work but I haven't 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 alos look at Continuation if you don't want to pass in callback functions.

like image 165
Tomas Jansson Avatar answered Oct 29 '22 11:10

Tomas Jansson