Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用async关键字并行调用方法?_C#_.net_Async Await - Fatal编程技术网

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

C# 如何使用async关键字并行调用方法?,c#,.net,async-await,C#,.net,Async Await,现在我有3种方法 IList<Car> cars = Service.GetCars(20); IList<Shoe> shoes = Service.GetShoes(20); IList<Bike> bike = Service.GetBikes(20); IList cars=Service.GetCars(20); IList shoes=服务。GetShoes(20); IList bike=Service.GetBikes

现在我有3种方法

    IList<Car> cars = Service.GetCars(20);
    IList<Shoe> shoes = Service.GetShoes(20);
    IList<Bike> bike = Service.GetBikes(20);
IList cars=Service.GetCars(20);
IList shoes=服务。GetShoes(20);
IList bike=Service.GetBikes(20);
我想用异步关键字并行调用并等待。我真的不知道该怎么做。下面是GetMethod的摘要。。。你把async关键字放在哪里?我在哪里创建任务?我想做的事情和异步js库一样简单

public IList GetCars(int num){
returnrepository.GetCars(num);
}

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

Task stuff1 = Task.Run(() => Service.GetStuff1());
...
Task.WaitAll(stuff1, stuff2, stuff3);

如果要同时调用这三个方法,则需要调用异步版本:

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.Run
,因为这实际上是通过使用线程池线程围绕同步代码包装异步调用。一般来说,这不是一个好的设计,因为最好让同步代码保持同步,并在使用点包装它,而不是“隐藏”它不是真正异步的事实。

因为这是一个“服务”调用,服务应该能够直接支持异步调用。使用它们比使用任务要好。如果可能,请运行,因为这样会触发调用的线程池线程。(这也利用了async/await)因此我不需要GetCarsMethod?@elranu中的关键字async如果
存储库
支持GetCars的异步版本,您可以直接返回它。如果你需要在那里做其他的工作,那么也许你需要它,但你不一定需要它。最后一个问题:如果等待是这样的,那么在另一个下面的一行。它会并行进行吗?或者直到汽车返回一个值,GetShoes才会被调用?在任务结束时做并不更好。什么时候(汽车、鞋子、自行车)?我建议使用
wait Task.whalll
来更好地传播错误并具有更多的确定性。@elranu因为我一次启动一个任务,然后等待它们,所以任务将同时运行。直到有了汽车,这三款车才会有结果,但这三款车将同时投入使用。
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;
public Task<IList<Car>> GetCars(int num)
{
    return Task.Run(() => repository.GetCars(num));
}