Erik Philips
Erik Philips

Reputation: 54618

Async calling with multiple contexts

So I have code pseudo-similar to (dependency injected):

public DbContextA DBA { get; set; } // SQL Server 1
public DbContextB DBB { get; set; } // SQL Server 2

I'm just now sure how I can most effectively do the following?

public Task<ActionResult> MyAction()
{
  var trucks = await DBA.GetTrucksAsync();
  var cars = DBA.GetCarsAsync();

  var cats = await DBB.GetCatsAsync();
  var dogs = DBB.GetDogsAsync();

  await TaskEx.WhenAll(cars, dogs);
}

Unless I'm mistaken this isn't optimal. I think it would be great to be able to do:

public Task<ActionResult> MyAction()
{
  IEnumerable<Truck> trucks;
  IEnumerable<Car> cars;
  IEnumerable<Cat> cats;
  IEnumerable<Dog> dogs

  var dba = Task.Run(async () => { trucks = await DBA.GetTrucksAsync(); } )
    .ContinueWith(async () => { cars = await DBA.GetCarsAsync(); } );

  var dbb = Task.Run(async () => { cats = await DBB.GetCatsAsync(); })
    .ContinueWith(async () => { dogs = await DBB.GetDogsAsync(); });

  await Task.WhenAll(dba, dbb);
}

But I can't test this at the moment (and I'm pretty sure it's wrong).

Upvotes: 1

Views: 184

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456322

Just add a couple methods to represent the dependencies:

private async Task<Tuple<IEnumerable<Truck>, IEnumerable<Car>>> GetVehiclesAsync()
{
  var trucks = await DBA.GetTrucksAsync();
  var cars = await DBA.GetCarsAsync();
  return Tuple.Create(trucks, cars);
}

private async Task<Tuple<IEnumerable<Cat>, IEnumerable<Dog>>> GetAnimalsAsync()
{
  var cats = await DBB.GetCatsAsync();
  var dogs = await DBB.GetDogsAsync();
  return Tuple.Create(cats, dogs);
}

public Task<ActionResult> MyAction()
{
  var vehiclesTask = GetVehiclesAsync();
  var animalsTask = GetAnimalsAsync();
  await Task.WhenAll(vehiclesTask, animalsTask);
}

Upvotes: 3

Related Questions