1

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).

4
  • 2
    Task.Run on ASp.NET will make it worst because you'll be releasing one thread just to switch to another one with the same characteristics. `TaskEx? What version of the framework are you running on? Commented Aug 7, 2015 at 6:26
  • You could use AsyncController, it is a little better if you need to do long running calls as it will free up the thread for the time it is waiting for the response. Commented Aug 7, 2015 at 9:34
  • @PauloMorgado Yeah that should have just been Task. I'm aware of the Task.Run() it was there to demonstrate what I was trying to do, not actually how to do it. Commented Aug 7, 2015 at 22:53
  • No, that should have been nothing! Commented Aug 8, 2015 at 7:12

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.