开发者

Windows Forms Updating Controls from other threads [duplicate]

开发者 https://www.devze.com 2023-03-31 00:07 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to update GUI from another thread in C#?
This question already has answers here: Closed 11 years ago.

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 i开发者_C百科t 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";

    }


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";
    }
}


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()

0

精彩评论

暂无评论...
验证码 换一张
取 消