1

所以这里是交易。我有所有实现相同的对象列表interface。让我们称之为这个列表things。因为每个thingin都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 关键字来实现我想要的,但我不知道如何。

4

1 回答 1

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.

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

于 2013-10-15T10:37:11.260 回答