How to write extension method which will make invocation list members in multicast C# delegate run sequentially?

If you use Func for you delegates rather than custom delegates you could write something like this:

public static class FuncHelper
{
    public static async Task RunSequential<T1>(this Func<T1,Task> del, T1 param1)
    {       
        foreach (var d in del.GetInvocationList().OfType<Func<T1, Task>>())
        {
            await d(param1);
        }
    }

    public static async Task RunSequential<T1, T2>(this Func<T1, T2, Task> del, T1 param1, T2 param2)
    {
        foreach (var d in del.GetInvocationList().OfType<Func<T1, T2, Task>>())
        {
            await d(param1, param2);
        }
    }

// Additional methods for more parameters go here

}

It does seem that you are trying to use delegates in ways they were not really intended. They aren't really supposed to control order or have the functions rely on each other to complete.

Probably better off making a custom collection, maybe override += and -= if you want some delegate like behavior.


The cause of your problem is that your delegates have a different set of parameters.

The solution is to create an extra delegate that contains the call inclusive the parameters, similar to the System.Windows.Forms.MethodInvoker delegate.

The only difference in your methodInvoker is that your methodInvoker is not a delegate that returns void, but a delegate that returns a Task.

The function in your extension class would be similar to your foreach:

public delegate task MethodInvoker();

static class DelegateExtensions
{
    public static async Task ExecuteDelegates(this IEnumerable<MethodInvoker> methodInvokers)
    {
        foreach (var methodInvoker in methodInvokers)
        {
            await methodInvoker();
        }
    }
}

Usage would be like:

public MyClass
{
    private async Task F1()
    {
        Debug.WriteLine("Begin F1");
        await Task.Delay(TimeSpan.FromSeconds(1));
        Debug.WriteLine("F1 Completed");
    }

    private async Task F2(TimeSpan waitTime)
    {
        Debug.WriteLine("Begin F2");
        await Task.Delay(waitTime);
        Debug.WriteLine("F2 Completed");
    }

    private async Task F3(int count, TimeSpan waitTime)
    {
         Debug.WriteLine("Begin F3");
        for (int i = 0; i < count; ++i)
        {
            await Task.Delay(waitTime);
        }
        Debug.WriteLine("F3 Completed");
    }
}

public async Task ExecuteMyFunctions()
{
    MyClass X = new MyClass();
    IEnumerable<MethodInvoker> myMethodInvokers = new MethodInvoker[]
    {
        () => X.F1(),
        () => X.F2(TimeSpan.FromSeconds(1)),
        () => X.F3(4, TimeSpan.FromSeconds(0.25)),
    }
    await myMethodInvokers.ExecuteDelegates();
}

Comments

  1. Valente

    • 2018/2/4

    If you use Func for you delegates rather than custom delegates you could write something like this: public static class FuncHelper { public 

  2. Lukas

    • 2017/12/19

    That is, both invocation members go off simultaneously, not awaiting each other. I need them await each other so the output would be: M1.A M1.B M2.A M2.B I tried this in place of await del(): foreach (MyDel member in del.GetInvocationList()) { await member(); } This works. However, I have lots of code places where this needs to be done.

  3. Juelz

    • 2018/7/20

    docs.microsoft.com › Docs › .NET › .NET API browser › System

  4. De Angelis

    • 2015/6/23

    A a = new A(); B b = new B(); C c = new C(); // For a, b, and c, call the following methods: // -- MethodA with an int argument // -- MethodA with a string argument // -- MethodB with no argument. // A contains no MethodA, so each call to MethodA resolves to // the extension method that has a matching signature.

  5. Gray

    • 2015/4/27

    Represents a multicast delegate; that is, a delegate that can have more than one element in its invocation list.

  6. Albert

    • 2016/4/3

    C# - Extension Method. Extension methods, as the name suggests, are additional methods. Extension methods allow you to inject additional methods without modifying, deriving or recompiling the original class, struct or interface. Extension methods can be added to your own custom class, .NET framework classes, or third party classes or interfaces.

  7. Ulises

    • 2018/10/2

    Expression Bodied Members in C# Generic List Class Range Methods in C# What is Multicast Delegate in C#?; How to create Multicast Delegates in C#? 

  8. Zachariah

    • 2020/4/25

    Firstly, you define the interface of the type for which you want to write the extension-method. In that interface, you declare the definition of extension-method which includes two things; 1) name, 2) return type. These steps can be illustrated as, interface Number {. thousandsSeperator (): String;

  9. Connor

    • 2019/4/28

    If a multicast delegate has a nonvoid return type, the caller receives the return value from the last method to be invoked. The preceding methods are still 

  10. Roman

    • 2019/3/18

    Implement the extension method as a static method with at least the same visibility as the containing class. The first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier. In the calling code, add a using directive to specify the namespace that contains the extension method class.

  11. Dominik

    • 2018/2/16

    You can define variables of delegate, just like other data type, that can refer to After setting a target method, a delegate can be invoked using the 

  12. Brett

    • 2020/12/10

    A C# extension methods allows developers to extend functionality of an existing type without creating a new derived type, recompiling, or otherwise modifying the original type. C# extension method is a special kind of static method that is called as if it was an instance methods on the extended type. In this article, we will create a class

  13. Isaias

    • 2016/12/21

    Delegates can also be used in “anonymous methods” invocation. methods whose return type and parameter-list matches with the delegate 

  14. Ambrose

    • 2021/3/10

    Objects helps us to access the member of a class or struct either they can be fields, methods or properties, by using the dot.

  15. Idris

    • 2018/3/11

    Multicast delegates can have multiple functions bound that all get called when Adds a function delegate to this multi-cast delegate's invocation list.

  16. Brian

    • 2017/3/30

    To represent a car in programming, we can create a class, Car, with four properties, Model, Type, Color, and Size. These are called members 

Comments are closed.

Recent Posts