关于c#:Windows Forms更新来自其他线程的控件

Windows Forms Updating Controls from other threads

本问题已经有最佳答案,请猛点这里访问。

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

我有一个计时器对象,我想定期更新一个作为标签的UI控件。但是它崩溃了,并说我需要在UI线程上更新它。有人能帮忙吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
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";

    }


(P)如果你用的是Net 3.5+,请使用"dispatcher"。Otherwise some thing like this should work:(p)字母名称


(P)For WPF,use a dispatcherttimer,for windows forms,I think system.windows.forms.timer should do what you're looking for.(p)(P)The difference of these two timers to the system.timers.timer-class is,that they raise the tick-event in the ui thread.如果你使用这个系统,Timers.Timer,you have to manually route your calls to ui elements to the UI thread.In WPF,use the dispatcher to do this.Usespatcher.Beginnivoke()。In winforms use control.Beginnivoke()(p)