5

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.

2
  • 1
    Your code actually run in parallel, so your question? Commented Aug 13, 2012 at 8:16
  • @CuongLe, see my answer. I think he wants to call the functions with parameters. Commented Aug 13, 2012 at 8:17

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

i need also callback mechanism that when Method1() will be finish then another function will alter me with status. can u put some light.
3

You should try something like this instead :

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

9 Comments

arguments passed is at your convenience ofc :)
That is also a nice solution if you want to start all threads at the "same" time.
Yes, thanks for pointing this out, I missed to specify it in my answer
See my updated answer, you don't actually need a to use ContinueWith (but it is an alternative). I would instead use an explicit callback if that is what you want by passing in a function to the method as argument.
@Thomas - "I need also callback " - then why isn't that part of the question?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.