【问题标题】:Windows Forms Updating Controls from other threads [duplicate]Windows 窗体从其他线程更新控件 [重复]
【发布时间】:2011-08-24 15:43:54
【问题描述】:

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

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

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

    }

【问题讨论】:

    标签: c# multithreading timer


    【解决方案1】:

    如果您使用的是 .NET 3.5+,请使用调度程序。否则这样的事情应该可以工作:

    private delegate void updateUIDelegate();
    
    public void updateUI()
    {
        if (lblAirTrack.InvokeRequired)
        {
            lblAirTrack.Invoke(new updateUIDelegate(updateUI));
        }
        else
        {
            lblAirTrack.Text = "Tracking: " + itemList.Count + " items";
        }
    }
    

    【讨论】:

    • 很好,如果 updateUI 有一些参数要传递怎么办。我试过解决这个问题,但总是出现 IDE 错误
    • 例如,如果它接受一个字符串,则将字符串参数添加到 updateUIDelegate 和 updateUI。然后,当您调用时: lblAirTrack.Invoke(new updateUIDelegate(updateUI), newParameterGoesHere);
    【解决方案2】:

    对于 WPF,使用 DispatcherTimer,对于 Windows 窗体,我认为 System.Windows.Forms.Timer 应该可以满足您的需求。

    这两个定时器与 System.Timers.Timer 类的区别在于,它们在 UI 线程中引发 Tick 事件。如果您使用 System.Timers.Timer,则必须手动将对 UI 元素的调用路由到 UI 线程。在 wpf 中,使用 Dispatcher 来执行此操作。使用Dispatcher.BeginInvoke()。在winforms中使用Control.BeginInvoke()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-29
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多