修复一个跨线程异常 [英] Fixing a Cross-Thread Exception

查看:109
本文介绍了修复一个跨线程异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助修复了跨线程异常。我使用的调用通常可以解决这个问题,但由于某种原因它不wokring:

 无效paintTimer_Elapsed(对象发件人,System.Timers.ElapsedEventArgs E)
{
    调用(新InvalidateFromSepThreadDel(InvalidateFromSepThread));
}
委托无效InvalidateFromSepThreadDel();
无效InvalidateFromSepThread()
{
    TailGraph.Invalidate();
}
 

引发异常的调用:

  

$ {例外跨线程操作无效:控制'XTailGraph   从一个线程比它创建线程的其他访问   在} {System.Exception的System.InvalidOperationException}

解决方案

调用将元帅回线的对照的(一个谁的invoke方法已使用)上创建。也就是说,确定一个控制并没有在错误的线程创建开始与等控制的还有在上述线程创建P>

此外,由于没有目标的的调用指定那将是 this.Invoke - 这可能是不合适的。

(或者如哈桑汗指出,考虑的WinForms定时器......回调将永远在计时器被创造了,在这种情况下,线程中运行。)

快乐编码。

I need some help fixing a cross-thread exception. I am using Invoke which usually solves this issue, but for some reason it is not wokring:

void paintTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    Invoke(new InvalidateFromSepThreadDel(InvalidateFromSepThread));
}
delegate void InvalidateFromSepThreadDel();
void InvalidateFromSepThread()
{
    TailGraph.Invalidate();
}

The exception is thrown on the Invoke:

$exception {"Cross-thread operation not valid: Control 'XTailGraph' accessed from a thread other than the thread it was created on."} System.Exception {System.InvalidOperationException}

解决方案

Invoke will marshal back the thread that control (the one who's Invoke method is being used) was created on. Make sure the other control was also created on said thread -- that is, make sure one control wasn't created on "the wrong thread" to begin with.

Also, since no target for Invoke was specified then it will be the this.Invoke of the containing object/class -- which might not be appropriate.

(Or as Hasan Khan pointed out, consider the WinForms timer... the callback will always run in the thread the timer was created on, in that case.)

Happy coding.

这篇关于修复一个跨线程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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