Justin Homes Justin Homes - 2 years ago 110
Vb.net Question

Multiple Task in one controller

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

Public ActionResult Index()

I was going to wrap each method with

and then do
before i Process and
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?


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

Answer Source

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;


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download