带计时器的文本框异常

时间:2011-02-06 14:35:28

标签: c# exception textbox timer

我的代码有问题。

它会产生此异常:

  

Text'抛出了类型的异常   “Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException

private void Form1_Load(object sender, EventArgs e)
{ 
    Timer = new System.Threading.Timer(
        TimerTick, null, TimeSpan.Zero, new TimeSpan(0, refresh , 0));
}

void TimerTick(object state)
{
    LoggerTxt.AppendText("fsjdaò");

 }

LoggerTxt是TextBox

我该怎么做?

感谢

2 个答案:

答案 0 :(得分:2)

您只能从前台线程中访问Windows窗体应用程序中的GUI组件。 (我认为,对于WPF应用程序也是如此)

由于您尝试从计时器函数(在后台线程中)调用TextBox(GUI组件)上的函数,您将获得异常。

尝试

LoggerTxt.Invoke( 
    new MethodInvoker( 
        delegate { LoggerTxt.AppendText("fsjdaò"); } ) );

避免例外。

另请参阅Control.Invoke的文档,了解有关此主题的更多信息以及this similar SO posting

答案 1 :(得分:1)

正如Uwe所评论的那样,您无法访问或修改GUI线程上的GUI组件,因此您通常必须调用它。

如果您打算这么做,为什么不将此类添加到项目中,以便所有控件对象都将此方法公开给它们。

您可以使用LoggerTxt.RunInGUIThread(x => x.AppendText("fsjdao"));

public static class ControlExtensions

{

  public static void RunInGUIThread<TControl>(this TControl control, Action<TControl> action)

    where TControl: Control

  {

    if (control.InvokeRequired)

      control.Invoke(action, control);

    else

      action(control);

  }

}