Thomas
Thomas

Reputation: 34188

The different use of Task Parallel library

I saw few people call function using syntax like:

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

And few people write code like:

Task myFirstTask = Task.Factory.StartNew(() => Method1(5));
Task mySecondTask = Task.Factory.StartNew(() => Method2("Hello"));

So my question is when one should use Parallel.Invoke() and when one should create instance of Task class and call StartNew() method.

Parallel.Invoke() looks very handy.so what is the significance of using Task class & StartNew() method.........put some light and tell me the importance of different approach for same kind of job means call two function parallel with two different syntax.

i never use before the Task Parallel library. so there could be some hidden reason for using two approach for calling function. please guide me in detail. thanks

Upvotes: 4

Views: 350

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499770

Well, Parallel.Invoke will block until both of the new tasks have completed.

The second approach will start two new tasks, but not wait for them to be completed. You could await them manually, or in C# 5 the new async/await feature will help you "wait" asynchronously.

It really depends what you want to do. If you want your thread to block until all the tasks have finished, Parallel.Invoke is handy.

Upvotes: 6

Related Questions