2009-04-17

Timer and GUI

One cannot use the System.Timers.Timer to update the GUI, instead one gets a cross-thread exception. The GUI can't be updated from another thread.

A nice trick to solve this is to use a method that is sensitive for if the call comes from another thread than the GUI is running on.



private delegate void SetTextDelegate(Label label, string text);

private void SetText(Label label, string text)
{
if (this.InvokeRequired)
{
IAsyncResult res = BeginInvoke(new SetTextDelegate(SetText), label, text);
EndInvoke(res);
}
label.Text = text;
}


Honor those who should.

No comments: