Textbox exception with timer
I have a problem with this code.
It's generates this exception:
Text' threw an exception of type '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开发者_Python百科ò");
}
LoggerTxt is a TextBox
.
How I can do?
thanks
You can access GUI components in a Windows Forms application only from within the foreground thread. (I think, this is also true for WPF applications)
Since you are trying to call a function on the TextBox
(a GUI component) from the timer function (in the background thread) you get the exception.
Try
LoggerTxt.Invoke(
new MethodInvoker(
delegate { LoggerTxt.AppendText("fsjdaò"); } ) );
To avoid the exception.
Also see the documentation of Control.Invoke
for more on this topic and this similar SO posting.
As Uwe has commented you cannot access or modify a GUI component not on the GUI thread therefore you have to usually invoke this.
If you are going to do this a lot why not add this class to your projects so that all control objects have this method exposed to them.
You can use 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);
}
}
精彩评论