I have 8 methods in an ASP.NET Console App, like Fun1()
, Fun2()
, Fun3()
… and so on. In my console application I have called all these methods sequentially. But now the requirement is I have do that using parallel programming concepts. I have read about task and threading concepts in Java but completely new to .NET parallel Programming.
Here is the flow of methods I needed in my console app,
As you can see the diagram, Task1
and Task2
should run in parallel, and Task3
will only occur after completion of the previous two.
The functions inside each task, for example Fun3
and Fun4
for the Task1
, should run sequentially, the one after the other.
Can anyone please help me out?
2
Answers
One way to solve this is, by using WhenAll.
To take an example, I have created X number of methods with the name FuncX() like this:
In this case, we have Func1, Func3, Func4, Func5, and Func6.
So we call methods and pass them to a list of Task.
You have 2 options to get the result:
This is just example for inspiration, you can change it and do it the way you want.
Here is how you could create the tasks according to the diagram, using the
Task.Run
method:The
Task.Run
invokes the delegate on theThreadPool
, not on a dedicated thread. If you have some reason to create a dedicated thread for each task, you could use the advancedTask.Factory.StartNew
method with theTaskCreationOptions.LongRunning
argument, as shown here.It should be noted that the above implementation has not an optimal behavior in case of exceptions. In case the
Fun3()
fails immediately, the optimal behavior would be to stop the execution of thetask2
as soon as possible. Instead this implementation will execute all three functionsFun1
,Fun5
andFun6
before propagating the error. You could fix this minor flaw by creating aCancellationTokenSource
and invoking theToken.ThrowIfCancellationRequested
after each function, but it’s going to be messy.Another issue is that in case both
task1
andtask2
fail, only the exception of thetask1
is going to be propagated through thetask3
. Solving this issue is not trivial.Update: Here is one way to solve the issue of partial exception propagation:
In case both
task1
andtask2
fail, thetask3
will propagate the exceptions of both tasks.