J.D. J.D. - 1 month ago 9
C# Question

How do I call two functions asynchronously, in parallel, in C#?

I've got two static functions that are independent of each other and consume a large amount of resources when they're used individually.

public static class Helper(){
public static void A(string username, int power, Model model)
{ /* do A things to the model */ }
public static void B(string username, Model model)
{ /* do B things to the model */ }
}


Right now, they're called as

public ActionResult Home(){
Model model = new Model();
A("Jared", 9001, model);
B("Jared", model);
return View("Home", model);
}


In my controller (attn: not real code).

I want them to work side by side, asynchronously, and then when they're both done I'd like to return to synchronous processing in order to return the View with the updated model.

Is there a way to accomplish this? I've never worked with asynchronous C# or threaded C# before, so it's been hard for me to decipher the examples I've uncovered.

TIA

Answer

This should do the trick..

public async Task<ActionResult> Home()
{ 
  var model = new Model();
  var t1 = Helper.A("Jared", 9001, model);
  var t2 = Helper.B("Jared", model);

  await Task.WhenAll(new [] { t1, t2 });

  return View("Home", model);
}

public static class Helper
{
  public static async Task A(string username, int power, Model model)
  {
    /* do A things to the model */ 
  }
  public static async Task B(string username, Model model)
  {
    /* do B things to the model */ 
  }
}

There's a big "gotcha" with this though. The model must be able to handle A() and B() working in parallel.