多线程的WinForms:是调用UI线程上的方法时,需要每次都创建一个新的委托? [英] Winforms multithreading: Is creating a new delegate each time when invoking a method on the UI thread needed?

查看:114
本文介绍了多线程的WinForms:是调用UI线程上的方法时,需要每次都创建一个新的委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要调用该操纵UI线程上的控件的方法。我的代码工作,我想优化。我指的是在MSDN上这资源。
结果
根据那里,我们应该做的。



 公共委托无效myDelegate(INT anInteger,串ASTRING); 
// ...
Label1.Invoke(新myDelegate(myMethod的),新的对象[] {1,这是字符串});



这会引入一个孤立的委托对象(内存泄漏),在每次调用<? / STRONG>



当我将与委托的静态实例做类似下面,然后使用这个实例在每次调用来调用:

 私有静态_delegateInstance =新myDelegate(myMethod的); 
// ...
Label1.Invoke(_delegateInstance,新的对象[] {1,这是字符串});



请问这是线程安全的?我想这是真实的,这有一个稍微好一点的性能,因为委托实例只创建一次?


解决方案

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




没有它不会,这是确定。



但为了避免每次创建一个代表,你可以使用一些的现有(如果你的方法需要2个字符串参数并没有返回):

  Label1.Invoke.Invoke((动作<字符串,字符串>)myMethod的,
新的对象[] {1,这是字符串});


I want to invoke a method that manipulates a control on the UI thread. My code works and I want to optimize. I am referring to this resource on MSDN.
According to there, we should do

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

Would this introduce an orphaned delegate object (a memory leak), at each call?

When I would do it with a static instance of the delegate like below and then use this instance at each call to invoke:

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

Would this be Thread-Safe? I would it be true that this has a slightly better performance, since the delegate instance is only created once?

解决方案

Would this introduce an orphaned delegate object (a memory leak), at each call?

No it won't, it is OK.

But to avoid creating a delegate each time you could use some of the existing (if your method takes 2 string parameters and has not return):

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

这篇关于多线程的WinForms:是调用UI线程上的方法时,需要每次都创建一个新的委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆