1

Possible Duplicate:
How to update GUI from another thread in C#?
My Timer event crashes because the events are called on a different thread

I have a timer object that I want to periodically update a UI control which is a label. However it crashes and says I need to update it on the UI thread. Can anyone help?

private void frmMain_Load(object sender, EventArgs e)
    {
        aTimer = new System.Timers.Timer(1000);          
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Interval = 2000;
        aTimer.Enabled = true;
   }
   public void updateUI()
    {

        lblAirTrack.Text = "Tracking: " + itemList.Count + " items";

    }
Community
  • 1
  • 1
Lee Armstrong
  • 11,420
  • 15
  • 74
  • 122

2 Answers2

2

For WPF, use a DispatcherTimer, for Windows forms, I think System.Windows.Forms.Timer should do what you're looking for.

The difference of these two timers to the System.Timers.Timer-class is, that they raise the Tick-event in the UI thread. If you use the System.Timers.Timer, you have to manually route your calls to UI elements to the UI thread. In wpf, use the Dispatcher to do this. UseDispatcher.BeginInvoke(). In winforms use Control.BeginInvoke()

HCL
  • 36,053
  • 27
  • 163
  • 213
2

If you're using .NET 3.5+, use the dispatcher. Otherwise something like this should work:

private delegate void updateUIDelegate();

public void updateUI()
{
    if (lblAirTrack.InvokeRequired)
    {
        lblAirTrack.Invoke(new updateUIDelegate(updateUI));
    }
    else
    {
        lblAirTrack.Text = "Tracking: " + itemList.Count + " items";
    }
}
jglouie
  • 12,523
  • 6
  • 48
  • 65
  • Nice, what if updateUI has some parameters to pass. I've tried working this out but always get IDE errors – Lee Armstrong Aug 24 '11 at 16:06
  • 1
    For example, if it took a string, add the string parameter to both updateUIDelegate and updateUI. Then, when you invoke: lblAirTrack.Invoke(new updateUIDelegate(updateUI), newParameterGoesHere); – jglouie Aug 24 '11 at 16:14