如何使用async关键字并行调用方法?

时间:2013-05-24 21:37:29

标签: c# .net async-await

现在我有3个方法

    IList<Car> cars = Service.GetCars(20);
    IList<Shoe> shoes = Service.GetShoes(20);
    IList<Bike> bike = Service.GetBikes(20);

我希望将调用与异步关键字并行等待。我真的不明白怎么做。以下是GetMethod的摘要...其中y放了async关键字?我在哪里创建任务?我想像async js lib一样简单。 https://github.com/caolan/async/

   public IList<Car> GetCars(int num){
        return repository.GetCars(num);
   }

2 个答案:

答案 0 :(得分:8)

如果要一次调用所有三种方法,则需要调用异步版本:

var carTask = Service.GetCarsAsync(20);
var showTask = Service.GetShoesAsync(20);
var bikeTask = Service.GetBikesAsync(20);
IList<Car> cars = await carTask;
IList<Shoe> shoes = await shoeTask;
IList<Bike> bike = await bikeTask;

前三行开始异步操作,每次返回Task<IList<T>>await调用“等待”完成并返回实际值。

您可以在同一行上写下这些内容,但是如上所述将它们拆分会导致所有三个异步操作立即启动,然后在结果返回时获取结果。如果你把它们放在同一行,即:IList<Car> cars = await Service.Get...,那么操作将保持异步,但第二行不会在第一次完成之前开始。

如果您自己编写方法,则需要打包电话。如果您没有现有异步方法的选项,可以将其包装起来:

public Task<IList<Car>> GetCars(int num)
{
    return Task.Run(() => repository.GetCars(num));
}

但是,如果你的repository支持异步方法,最好直接使用它们而不是调用Task.Run,因为这实际上是通过使用ThreadPool线程在同步代码周围进行异步调用。一般来说,这不是一个好的设计,因为最好保持同步代码同步并将其包装在使用点,而不是“隐藏”它并非真正异步的事实。

答案 1 :(得分:0)

为每个方法创建一个任务,等待它们:

Task stuff1 = Task.Run(() => Service.GetStuff1());
...
Task.WaitAll(stuff1, stuff2, stuff3);
相关问题