异步调用许多方法,并在每个方法完成时执行某些操作

时间:2013-10-15 10:32:51

标签: c# task

所以这是交易。我有所有实现相同interface的对象列表。让我们调用此列表things。由于thing中的每个things实现了相同的接口,我知道他们有方法调用DoStuff(StuffParams stuffParams)。我想异步地为每个thing调用此方法,并在每个方法完成时执行某些操作。所以更具体一点。

public void CreateSomething(Something something)
{
    ValidateSomething(something);

    someDAL.AddSomething(something);

    AddSomethingToMonitor(something);

    var things = someService.GetThings(); 
    // every thing in things has method DoStuff

    // invoke thing.DoStuff for each thing in things and return to caller
}

// when those methods return something should happen
// but I don't know where to write that code. Inside CreateSomething or outside.

我想我应该使用async和await关键字来实现我想要的但我不知道如何。

1 个答案:

答案 0 :(得分:3)

有几种可能性,包括任务和.ContinueWith(),但最直接的方法是:

Parallel.ForEach (things, thing => 
{
    // Invoke thing.DoStuff with some specific parameters asynchronously.

    // Do something when a single one returns
});

// Do something when all  methods have returned.

与例如的变化取消是可能的。