Different uses of a parallel task library

I saw several people call a function using syntax like:

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

And few write code like:

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

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

Parallel.Invoke () looks very convenient. What is the importance of using the Task class and the StartNew () method ......... put some light and tell me that the importance of a different approach for the same kind of work means calling two functions in parallel with two different syntaxes.

I never use in front of a parallel task library . therefore, there may be a hidden reason for using two approaches to call a function. please guide me in detail. thanks

+4
source share
1 answer

Well, Parallel.Invoke will block until both new tasks are completed.

The second approach will launch two new tasks, but does not wait for their completion. You can wait for them manually, or in C # 5, the new async / await function will help you to "wait" asynchronously.

It really depends on what you want to do. If you want your thread to block until all tasks are completed, Parallel.Invoke convenient.

+6
source

All Articles