Invoke method in C#

Question raised: What does .Invoke() mean.
The answer is as follows:

 //C# 5
var handler = Event;
if (handler != null)
{
    
    
handler(source, e);
}
//C# 6
var handler = Event;
handler?.Invoke(source, e);

At the same time, I also think of the UI thread, there is also invoke, what is the difference? So the summary is as follows:

In C#, the Invoke method can be used in a variety of situations such as delegate invocation, control of UI thread operations, and reflection invocation. How to use it depends on the context and the types involved.
1. Invoke method of the delegate: The delegate type has a method called Invoke, which is used to call the method referenced by the delegate. For example, if you have a delegate myDelegate, you can use myDelegate.Invoke() to execute the method referenced by the delegate.
delegate void MyDelegate(string message);

void PrintMessage(string message)
{
    
    
    Console.WriteLine(message);
}

MyDelegate myDelegate = PrintMessage;
myDelegate.Invoke("Hello, World!"); // 使用 Invoke 方法调用委托引用的方法

2. The Invoke method to control the UI thread: In Windows Forms or WPF applications, if you process UI elements on a non-UI thread
, you need to use the Invoke method to switch the operation to the UI thread to avoid thread safety issues. This is because UI
elements can generally only be accessed and modified on the thread that created them.

void UpdateUI(string message)
{
    
    
    if (textBox.InvokeRequired)
    {
    
    
        textBox.Invoke(new Action<string>(UpdateUI), message); // 使用 Invoke 方法切换到 UI 线程
    }
    else
    {
    
    
        textBox.Text = message;
    }
}

3. The Invoke method in reflection: In reflection, you can use the Invoke
method to call the method of the object, get or set the property value of the object, and so on. This makes it possible to call and manipulate objects dynamically at runtime.

MethodInfo methodInfo = typeof(MyClass).GetMethod("MyMethod");
object result = methodInfo.Invoke(instance, parameters); // 使用 Invoke 方法调用方法

Guess you like

Origin blog.csdn.net/weixin_41487423/article/details/131415017