SoFunction
Updated on 2025-04-12

Differences and connections between Invoke/BeginInvoke/EndInvoke and DynamicInvoke methods in C# commission

Preface

In C#, delegate provides a variety of calls, includingInvokeBeginInvokeEndInvokeandDynamicInvoke. Each calling method has its own specific purpose and applicable scenarios. The differences and connections between these methods will be described in detail below.

1. Invoke method

1. Definition

InvokeIt is a method that calls delegate synchronously. It blocks the current thread until the delegate's referenced method is executed and returns the result.

2. Features

  • Synchronous call: The current thread will be blocked until the delegate method execution is completed.
  • Simple and direct: Suitable for scenarios where asynchronous processing is not required.

3. Sample code

public class Program
{
    public static void Main()
    {
        // Define the delegation        Action action = () => ("Hello, World!");
        // Synchronous call        ();
    }
}
public class Program
{
    public delegate string SimpleDelegate(string message);
    public static string PrintMessage(string message)
    {
        ($"Message: {message}");
        return "Done";
    }
    public static void Main()
    {
        SimpleDelegate del = PrintMessage;
        string result = ("Hello, World!"); // Synchronous call        (result);
    }
}

Output result

Message: Hello, World!
Done

2. BeginInvoke and EndInvoke methods

1. Definition

BeginInvokeandEndInvokeMethods are used to asynchronously call methods referenced by delegates.BeginInvokeMethod starts an asynchronous operation and returns an immediatelyIAsyncResultObject, which can be used to track the status of asynchronous operations. andEndInvokeMethods are used to get the result of an asynchronous call or wait for the asynchronous call to complete.

2. Features

BeginInvoke

  • Asynchronous call: The current thread will not be blocked, and the delegate method will be executed on the background thread.
  • Callback mechanism: The callback function can be automatically called after the delegate method is completed by providing a callback function.
  • Parameter pass: In addition to the delegate method parameters, you also need to pass aAsyncCallbackDelegate and a user-defined object (usuallynull)。

EndInvoke

  • Get results: By incomingBeginInvokeReturnedIAsyncResultObject to get the result of an asynchronous call.
  • Wait for completion: If the asynchronous call has not been completed yet,EndInvokeThe current thread will be blocked until the asynchronous call completes.

3. Sample code

using System;
public class Program
{
    public delegate string SimpleDelegate(string message);
    public static string PrintMessage(string message)
    {
        ($"Message: {message}");
        return "Done";
    }
    public static void Main()
    {
        SimpleDelegate del = PrintMessage;
        IAsyncResult asyncResult = ("Hello, World!", null, null); // Asynchronous call        ("Main method continues...");
        // Wait for the asynchronous call to complete and get the result        string result = (asyncResult);
        (result);
    }
}

Output result

Main method continues...
Message: Hello, World!
Done

using System;
using ;
public class Program
{
    public static void Main()
    {
        // Define the delegation        Func<int> func = () =>
        {
            (2000);
            ("Asynchronous operation completed.");
            return 42;
        };
        // Asynchronous call        IAsyncResult result = (null, null);
        // Perform other operations        ("Performing other tasks while waiting...");
        // Wait for the asynchronous operation to complete and get the result        int returnValue = (result);
        ($"Return value: {returnValue}");
    }
}

3. DynamicInvoke method

1. Definition

DynamicInvokeIt is a method that dynamically calls delegates, allowing delegates to be called with arbitrary types of parameters without specifying specific parameter types.
andInvokedifferent,DynamicInvokeThe method to be called dynamically can be determined at runtime, and the types of parameters and return values ​​can be processed.

2. Features

  • High flexibility: The parameter type and number can be determined dynamically at runtime.
  • Low performance: Due to the need for type checking and conversion, the performance is usually lower than direct calls (e.g.InvokeorBeginInvoke)。

3. Sample code

using System;
public class Program
{
    public delegate string SimpleDelegate(string message);
    public static string PrintMessage(string message)
    {
        ($"Message: {message}");
        return "Done";
    }
    public static void Main()
    {
        SimpleDelegate del = PrintMessage;
        object[] args = new object[] { "Hello, DynamicInvoke!" };
        string result = (string)(args); // Dynamic call        (result);
    }
}

Output result

Message: Hello, DynamicInvoke!
Done

using System;
public class Program
{
    public static void Main()
    {
        // Define the delegation        Func<int, int, int> add = (a, b) => a + b;
        // Dynamic call        object result = (2, 3);
        ($"Result: {result}");	//Output: Result: 5    }
}

4. Comparison and summary

1. Overview

method Call method Whether to block the current thread Parameter type requirements performance Main application scenarios
Invoke synchronous yes fixed high Simple synchronous call
BeginInvoke asynchronous no fixed medium Asynchronous call
EndInvoke synchronous yes fixed medium Get the result of an asynchronous call
DynamicInvoke dynamic yes dynamic Low Dynamic call at runtime

2. Specific differences and connections

Invoke vs BeginInvoke

  • InvokeIt is a synchronous call that will block the current thread until the method execution is completed;BeginInvokeIt is an asynchronous call that will not block the current thread.
  • InvokeApplicable to scenarios where results need to be obtained immediately;BeginInvokeSuitable for scenarios where response speed is needed to be improved and the main thread is avoided.

BeginInvoke vs EndInvoke

  • BeginInvokeUsed to start an asynchronous call, return aIAsyncResultObject;EndInvokeUsed to get the result of an asynchronous call or wait for the asynchronous call to complete.
  • In useBeginInvokeAfter that, it must be calledEndInvoketo ensure resource release and obtain results.

DynamicInvoke

  • DynamicInvokeProvides great flexibility, but at the cost of low performance, as it requires type checking and conversion at runtime.
  • Suitable for scenarios where parameter types and quantity need to be determined dynamically at runtime.

3. Practical application suggestions

  • Synchronous call: If you need to get the result immediately and don't care about blocking the current thread, useInvoke
  • Asynchronous call: If you want to perform an operation without blocking the current thread, useBeginInvokeandEndInvoke
  • Dynamic call: If you need to dynamically determine the parameter type and quantity at runtime, useDynamicInvoke, but pay attention to its performance overhead.
  • Real-time data display:useAsynchronously update the UI.
  • Batch calculation tasks:passBeginInvokeDistribute tasks to thread pool.
  • Plug-in system: CombinedDynamicInvokeImplement dynamic method calls.

By rationally choosing the calling method, you can improve program performance and response speed while ensuring thread safety.

4. Contact and collaborate

  • Asynchronous call chain:
  • BeginInvoke starts an asynchronous task → monitor status through IAsyncResult → obtain results to form a complete asynchronous process.
  • Thread Safety:
  • During UI control operations, and force delegates to be executed in UI threads to avoid cross-thread access exceptions.
  • Alternatives:
  • Modern C# recommends using Task and async/await instead of BeginInvoke/EndInvoke because its code is more readable and resource management is safer.

5. Things to note

Performance overhead

  • BeginInvokeRelying on thread pools, frequent calls may lead to resource competition;DynamicInvokeThe reflection mechanism is low in efficiency and is cautiously used in high-frequency scenarios.

Exception handling

  • InvokeandDynamicInvokeThe exception is directly transmitted, and it needs to betry-catchpack;
  • BeginInvokeThe exception needs to beEndInvokeCaptured in.

Code optimization
In publishing mode, the compiler may inline the method, which can be passed[MethodImpl()]Keep stack information.

This is the article about the Invoke/BeginInvoke/EndInvoke and DynamicInvoke methods in C# commission. For more related contents of C# commission Invoke/BeginInvoke/EndInvoke and DynamicInvoke, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!