Suppose that we have three functions as below:
public static void A() => Console.WriteLine("A");
public static void B() => Console.WriteLine("B");
public static void C() => Console.WriteLine("C");
You can use the following approach:
var task = Task.Run(A)
.ContinueWith(t => B(), TaskContinuationOptions.NotOnFaulted)
.ContinueWith(t => C(), TaskContinuationOptions.NotOnFaulted);
task.Wait();
Which will executes the A()
and if it executes successfully, then will execute B()
and if it succeeded to then C()
will be executed. If any exception occurred while executing A()
or B()
, the children tasks will not be executed.
Thanks to @AlexeiLevenkov, if these methods are doing some CPU intensive works, then paralleling them will give you notable performance benefits, otherwise paralleling might have negative impact on your work!
Microsoft says:
When parallelizing any code, including loops, one important goal is to
utilize the processors as much as possible without over parallelizing
to the point where the overhead for parallel processing negates any
performance benefits
Read more here: https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-write-a-simple-parallel-for-loop#matrix-and-stopwatch-example