C#的计时器执行中的多线程问题

c#中有两个计时器,一个在FORM使名空间,一个在System命名空间。

一般前者在window form 应用中使用,后者在window service,后台管理中使用。

常见问题之一:计时器执行时间比间隔要大时出现多线程问题。

  private void timer1_Tick(object sender, EventArgs e)
  {

           lock(o)
            {
                try
                {
                    if (GrobalManage.gmstepindex < GrobalManage.gmstepcount - 1)
                    {
                        GrobalManage.gmstepindex++;
                        if (MeshSetting.isContourShow && MeshSetting.variable_index != 0)
                        {
                            GrobalManage.IGetCurrentStepData(MeshSetting.variable_index - 1, GrobalManage.gmstepindex);
                        }
                        ComboBox_timeStep.SelectedIndex = GrobalManage.gmstepindex;
                        MyMapView.tick();    //这个函数执行时间比计时器间隔要大。                    
                        ProgressBar.Maximum = GrobalManage.gmstepcount - 1;
                        ProgressBar.Value = GrobalManage.gmstepindex;
                    }
                    else
                    {
                        timer1.Enabled = false;
                    }
                }
                catch (Exception err)
                {
                    timer1.Enabled = false;
                }
            }
        }
如上运行后还是出现多线程问题,在MyMapView.tick()这个函数内增加线程控制后问题解决。

原文地址:https://www.cnblogs.com/wangrsh2010/p/2088619.html