调用时C#无效的跨线程调用? [英] C# invalid cross thread call while invoking?!

查看:116
本文介绍了调用时C#无效的跨线程调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好!

我使用以下方法来调用某些内容:

Hello!

I use the following method to invoke something:

public void InvokeHelper(object from, object to)
        {
            BeginInvoke(new MethodInvoker(delegate()
            {
                from = to;
            }));
        }



但有时会抛出一个无效的crossthreadcall异常.我大约每秒使用50次.

所以问题是为什么它会引发异常?



But sometimes it throws an invalidcrossthreadcall exception. I use it about 50 times a second.

So the question is why is it throw exception?

推荐答案

尝试这样写:
Try writing it like this:
public void InvokeHelper(object from, object to)
{
 BeginInvoke( (MethodInvoker) delegate { from = to; });
}



问候
Espen Harlinn



Regards
Espen Harlinn


我建​​议首先检查是否有必要.您可能还需要检查IsHandleCreated以确保已创建控件.请查看第一个链接以获取有关此信息的更多信息,并查看第二个链接作为示例.

I would suggest to first check if it is necessary. You might also need to check IsHandleCreated to ensure that the control is created. Have a look at the first link for more info on that and for an example check the second link.

if(this.InvokeRequired)
{
  this.BeginInvoke(method);
} else
{
  method();
}



http://msdn.microsoft.com/nl-nl/library/system.windows.forms.control.invokerequired.aspx [ ^ ]

http://msdn.microsoft.com/nl-nl/library/ms171728.aspx [ ^ ]

祝你好运!



http://msdn.microsoft.com/nl-nl/library/system.windows.forms.control.invokerequired.aspx[^]

http://msdn.microsoft.com/nl-nl/library/ms171728.aspx[^]

Good luck!


您可能还需要考虑上下文


you might want to consider the context as well


public void InvokeHelper(object from, object to, System.Threading.SynchronizationContext context)
        {

              _conex.Post(new SendOrPostCallback((obj) => {
                                                     
                     //your code here
                     }
              ), null);

        }


这篇关于调用时C#无效的跨线程调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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