1

Looking for the best way to implement something like the Multicast delegate functionally for async Func functions.

Originally my custom builder used a Multicast delegate to register Start and Stop events like this:

public class {
 private Action<ConfigObj> startEvents;
 public AddStartEvent(Action<ConfigObj> newStart)
 {
  startEvents+=newStart;
 }
 public Start()
 {
  startEvents?.Invoke(config);
 }
}

What is the best way to do this with async Func lambdas? I have implemented something that works.

private List<Func<ConfigObj,Task>> at;
...
public Task RunFuncs()
        {
            if (at.Count == 0) {
                return Task.CompletedTask;
            }
            else
            {
                Task[] tasks = new Task[at.Count];
                int ind = 0;
                foreach(var t in at)
                {
                    tasks[ind] = t.Invoke(configObj);
                    ind++;
                }
                return Task.WhenAll(tasks);
            }
        }

Is there a better way to do this?

Xvoo
  • 13
  • 2
  • 2
    *All* delegates are multicast delegates, whether the signature is asynchronous or not. – Servy Jun 10 '19 at 19:46
  • @Servy That's true, but I assume what's unstated by the question is that using the standard Invoke on a multicast delegate doesn't work because you will only get the task for the last delegate in the invocation list. From the code shown they want to await all the tasks. – Mike Zboray Jun 10 '19 at 20:09
  • 1
    @MikeZboray But that's *not* what the question indicates. Between not using a delegate, but rather a list of multicast delegates, and asking how to make a multicast delegate for an async function, they're *not* asking how to get all of the returned values from a multicast delegate when invoking it, and appear to not realize that the delegate is *already* a multicast delegate. There are of course any number of duplicate questions showing how to do precisely that if that's what they want. – Servy Jun 10 '19 at 20:20
  • It's hard to really understand the question, and questions of the form "this works, is there something better" are generally too broad for SO in any case. But, your "original" implementation has a strong similarity to C# events. That along with your apparent desire to invoke the delegates asynchronously suggests that [this answer](https://stackoverflow.com/a/27763068) I wrote some time ago might be of use. – Peter Duniho Jun 10 '19 at 21:19
  • @PeterDuniho your reply was what I was looking for thanks. – Xvoo Jun 14 '19 at 19:19
  • Great...I'll close this question since the other one answers it. We can leave this question as a signpost to help people find the other one. – Peter Duniho Jun 15 '19 at 01:20

0 Answers0