Winforms多线程:每次在UI线程上调用方法时都要创建一个新的委托吗?

Mar*_*cel 5 c# multithreading delegates invoke winforms

我想调用一个操作UI线程控件的方法.我的代码有效,我想优化.我指的是MSDN上的这个资源.
根据那里,我们应该这样做

public delegate void myDelegate(int anInteger, string aString);
//...
Label1.Invoke(new myDelegate(myMethod), new Object[] {1, "This is the string"});
Run Code Online (Sandbox Code Playgroud)

这会在每次调用时引入一个孤立的委托对象(内存泄漏)吗?

当我像下面这样使用委托的静态实例时,然后在每次调用时使用此实例来调用:

private static _delegateInstance = new myDelegate(myMethod);
//...
Label1.Invoke(_delegateInstance , new Object[] {1, "This is the string"});
Run Code Online (Sandbox Code Playgroud)

这是线程安全吗?我认为这会有更好的性能,因为委托实例只创建一次?

Dar*_*rov 1

这会在每次调用时引入一个孤立的委托对象(内存泄漏)吗?

不,不会的,没关系。

但为了避免每次都创建委托,您可以使用一些现有的委托(如果您的方法采用 2 个字符串参数并且未返回):

Label1.Invoke.Invoke((Action<string, string>)myMethod, 
    new object[] { 1, "This is the string" });
Run Code Online (Sandbox Code Playgroud)