Justin Homes Justin Homes - 6 months ago 33
Vb.net Question

Multiple Task in one controller

I have a MVC controller action that does n number of steps
like

Public ActionResult Index()
{
GetDatFromTabelCustomer()
GetDataFromWebApi()
GetDataFromSession()
GetyetAnotherData()
SendItToView()
}


I was going to wrap each method with
Task.Run

and then do
Task.WhenAll()
before i Process and
SendItToView()
.
But there are lot of blogs about why you should not use Task.Run
and instead do async await, in this scenario i really do want to run parallel task instead of await on each one in serial fashion,
there is some cost to stitch and tear-down thread from thread pool in doing so, but what other option do i have than doing Task.Run?

Example

Public ActionResult Index()
{
Task taska = Task.Run(() => GetDatFromTabelCustomer())
Task taskb = Task.Run(() => GetDataFromWebApi())
Task taskc = Task.Run(() => GetDataFromSession())
Task taskd = Task.Run(() => GetyetAnotherData())
await taska;
await taskb;
await taskc;
await taskd;

string get resultA = taska.Result
.
.
.
SendItToView()
}

Answer

The "correct" way to do it would be re-write your functions to be async than can be re-written to async, you can use Task.Run() for ones that don't expose a async API. You can also use Task.WhenAll( to combine all of the tasks in to one awaitable thing.

public async Task<ActionResult> IndexAsync()
{
    Task<string> taska = GetDatFromTabelCustomerAsync());
    Task taskb = GetDataFromWebApiAsync());
    Task taskc = Task.Run( () =>     GetDataFromSession());
    Task taskd = Task.Run( () =>      GetyetAnotherData());

    await Task.WhenAll(taska, taskb, taskc, taskd);

    string resultA = await taska;

    SendItToView()
}

In your example you showed taska returning a string, I fixed the code to do that. There is no cost to call await a 2nd time on a task and it is a better habit to have than to call taska.Result, you should never do a .Result from inside a async method.

Here is a good article explaining how to convert from synchronous MVC code to async MVC code

Comments