使用多个上下文进行异步调用

时间:2015-08-07 03:30:35

标签: asp.net-mvc async-await entity-framework-6 dbcontext

所以我的代码伪类似于(依赖注入):

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

我现在确定如何最有效地执行以下操作?

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);
}

除非我弄错了,否则这不是最佳选择。我认为能够这样做会很棒:

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);
}

但我现在无法对此进行测试(而且我非常确定这是错误的。)

1 个答案:

答案 0 :(得分:3)

只需添加几个方法来表示依赖项:

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);
}