Suprateem Bose
Suprateem Bose

Reputation: 69

How to run multiple methods in parallel in ASP.NET

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 to 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,

Diagram

As you can see in 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 Task1, should run sequentially, one after the other.

Can anyone please help me out?

Upvotes: 3

Views: 1708

Answers (2)

Theodor Zoulias
Theodor Zoulias

Reputation: 43475

Here is how you could create the tasks according to the diagram, using the Task.Run method:

Task task1 = Task.Run(() =>
{
    Fun3();
    Fun4();
});
Task task2 = Task.Run(() =>
{
    Fun1();
    Fun5();
    Fun6();
});
Task task3 = Task.Run(async () =>
{
    await Task.WhenAll(task1, task2);
    Fun7();
    Fun8();
});

The Task.Run invokes the delegate on the ThreadPool, not on a dedicated thread. If you have some reason to create a dedicated thread for each task, you could use the advanced Task.Factory.StartNew method with the TaskCreationOptions.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 the task2 as soon as possible. Instead this implementation will execute all three functions Fun1, Fun5 and Fun6 before propagating the error. You could fix this minor flaw by creating a CancellationTokenSource and invoking the Token.ThrowIfCancellationRequested after each function, but it's going to be messy.

Another issue is that in case both task1 and task2 fail, only the exception of the task1 is going to be propagated through the task3. Solving this issue is not trivial.


Update: Here is one way to solve the issue of partial exception propagation:

Task task3 = Task.WhenAll(task1, task2).ContinueWith(t =>
{
    if (t.IsFaulted)
    {
        TaskCompletionSource tcs = new();
        tcs.SetException(t.Exception.InnerExceptions);
        return tcs.Task;
    }
    if (t.IsCanceled)
    {
        TaskCompletionSource tcs = new();
        tcs.SetCanceled(new TaskCanceledException(t).CancellationToken);
        return tcs.Task;
    }
    Debug.Assert(t.IsCompletedSuccessfully);
    Fun7();
    Fun8();
    return Task.CompletedTask;
}, default, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default)
    .Unwrap();

In case both task1 and task2 fail, the task3 will propagate the exceptions of both tasks.

Upvotes: 3

Maytham Fahmi
Maytham Fahmi

Reputation: 33397

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:

async static Task<int> FuncX()
{
    await Task.Delay(500);
    var result = await Task.FromResult(1);
    return result;
}

In this case, we have Func1, Func3, Func4, Func5, and Func6.

So we call methods and pass them to a list of Task.

var task1 = new List<Task<int>>();

task1.Add(Func3());
task1.Add(Func4());

var task2 = new List<Task<int>>();

task2.Add(Func1());
task2.Add(Func5());
task2.Add(Func6());

You have 2 options to get the result:

// option1
var eachFunctionIsDoneWithAwait1 = await Task.WhenAll(task1);
var eachFunctionIsDoneWithAwait2 = await Task.WhenAll(task2);
var sum1 = eachFunctionIsDoneWithAwait1.Sum() + eachFunctionIsDoneWithAwait2.Sum();
Console.WriteLine(sum1);

// option2
var task3 = new List<List<Task<int>>>();
task3.Add(task1);
task3.Add(task2);
var sum2 = 0;
task3.ForEach(async x =>
{
    var r = await Task.WhenAll(x);
    sum2 += r.Sum();
});

Console.WriteLine(sum2);

This is just example for inspiration, you can change it and do it the way you want.

Upvotes: 3

Related Questions