Dimitri
Dimitri

Reputation: 2858

Invoke many methods asynchronously and do something when each of them is complete

So here is the deal. I have list of objects which all implement the same interface. Lets call this list things. since every thing in things implements the same interface I know that they have the method call DoStuff(StuffParams stuffParams). I would like to invoke this method for each thing asynchronously and do something whenever each of them is complete. So to be more specific.

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.

I suppose I should use async and await keywords to achieve what I want but I have no Idea how.

Upvotes: 1

Views: 72

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273219

There are several possibilities, including Tasks and .ContinueWith() but the most direct approach would be:

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.

Variations with e.g. Cancellation are possible.

Upvotes: 3

Related Questions