【发布时间】:2013-05-19 15:55:32
【问题描述】:
我有一个方法可以执行 2 个独立 逻辑。我希望我可以同时运行它们 .. 并且只有在这两个子方法都完成后才能继续。
我试图理解 async/await 语法,但我就是不明白。
代码如下:
public PewPew SomeMethod(Foo foo)
{
var cats = GetAllTheCats(foo);
var food = GetAllTheFood(foo);
return new PewPew
{
Cats = cats,
Food = food
};
}
private IList<Cat> GetAllTheCats(Foo foo)
{
// Do stuff, like hit the Db, spin around, dance, jump, etc...
// It all takes some time.
return cats;
}
private IList<Food> GetAllTheFood(Foo foo)
{
// Do more stuff, like hit the Db, nom nom noms...
// It all takes some time.
return food;
}
因此,使用上面的代码,我想说:去同时获取所有的猫和食物。完成后,返回一个新的PewPew。
我很困惑,因为我不确定上面的哪些类是 async 或返回 Task 等等。全部?只有两个私人的?我也猜想我需要利用 Task.WaitAll(tasks) 方法,但我不确定如何设置任务同时运行。
建议,好心人?
【问题讨论】:
-
Foo foo将在线程之间共享。确保您lock 正确。
标签: c# .net task async-await multitasking