我想调用一个方法来操作 UI 线程上的控件。我的代码有效,我想优化。我指的是这个 resource on MSDN .
根据那里,我们应该做
public delegate void myDelegate(int anInteger, string aString);
//...
Label1.Invoke(new myDelegate(myMethod), new Object[] {1, "This is the string"});
这会在每次调用时引入一个孤立的委托(delegate)对象(内存泄漏)吗?
当我像下面这样使用委托(delegate)的静态实例时,然后在每次调用时使用这个实例来调用:
private static _delegateInstance = new myDelegate(myMethod);
//...
Label1.Invoke(_delegateInstance , new Object[] {1, "This is the string"});
这会是线程安全的吗?由于委托(delegate)实例仅创建一次,因此我认为这确实具有更好的性能吗?
最佳答案
上面的两个答案给出了一些见解。有一篇好文章here如果您想获得更深入的信息。
这两种方法都是线程安全的,因为在调用时线程池会为每个调用分配一个线程。存在锁定的可能性,但如果您阅读了那篇文章,则可以找到解决方法。
此外,您需要记住,.Net 处理 UI 线程的方式略有不同。如果您正在处理 WPF,则必须考虑调度程序。参见 here .
最终,我不确定您是否会通过第二段代码获得巨大的性能提升,因此我倾向于坚持使用第一段。
N.
关于c# - Winforms 多线程 : Is creating a new delegate each time when invoking a method on the UI thread needed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4283689/