试图从计时器调用的方法中设置标签,在同一表单上出错



我有一个计时器,当它被触发时,将标签设置为可见。当我调用执行此操作的方法时,它会给出以下异常:

跨线程操作无效:控件"Startup2"是从创建它的线程以外的线程访问的。

我的计时器:

void GpsTimerElapsed(object sender, ElapsedEventArgs e)
{
  if (!ServicesConfig.MiscClasses.VerifyInternetAccess.HasInternet())
  {
    toolStripStatusLabel_Status.Text = "Internet not available!!";
    _history.History = "GPS Readings - Internet access not available.";
    HasError();
    return;
  }
  toolStripStatusLabel_Status.Text = "Processing GPS data.";
   _history.History = "GPS Readings - Timer ticked...";
  _gpsTimer.Stop();
  _history.History = "GPS Readings - Timer stopped...";
  var process = new ProcessGpsFile();
  _history.History = "GPS Readings - Timer processing Reading started...";
  if (process.ProcessReading()) HasError();
  _history.History = "GPS Readings - Timer processing Reading finished...";
  _gpsTimer.Start();
  _history.History = "GPS Readings - Timer started.";
  _history.History = "--------------------------------------------------------";
  toolStripStatusLabel_Status.Text = "Process GPS data complete.";
}

我的标签方法:

private void HasError()
{
  pictureBox_Status.Image = Properties.Resources.yellow;
  label_ClickToSeeError.Visible = true;
}

我不想假设,但这是否意味着计时器在自己的线程上运行,与表单分离?我该如何解决这个问题?

再次感谢!

您使用的是在线程池上运行的System.Timers.Timer
您应该将其替换为在UI线程上运行的System.Windows.Forms.Timer

最新更新