简体   繁体   中英

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.

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.

You should try something like this instead :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM