如何在不暂停GUI的情况下在计时器内运行不同的计时器



我有一个类SendCountingInfo(),它将每5分钟向服务器发送一条消息。这个类中的代码是:

public void StartSendCountingInfo()
{
      DoStartSendCountingInfo(300000);
}
private void DoStartSendCountingInfo(int iMiSecs)
{
      _pingTimer = new System.Timers.Timer(iMiSecs);
      _pingTimer.Elapsed += new System.Timers.ElapsedEventHandler(pingTimer_Elapsed);
      _pingTimer.Start();
}
void pingTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    PingRemoteHost();
}

当我尝试在Windows窗体类中调用它时,它不起作用。但是,当我删除计时器并直接调用PingRemoteHost()时,它就可以工作了。但是,表单加载不正确。它显示空白屏幕,但方法PingRemoteHost()可以工作。

这是windows表单中的代码:

private void Layout_Load(object sender, EventArgs e)
{
     tSystemChecker = new System.Timers.Timer(1000);
     tSystemChecker.Elapsed += new System.Timers.ElapsedEventHandler(tSystemChecker_Elapsed);
     tSystemChecker.Start();
     this.WindowState = FormWindowState.Maximized;
}
void tSystemChecker_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    UIThreadWork(this, delegate
    {
        try
        {
             SuspendLayout();
             DoCheckHardwareStatus();
             DoCheckLanguage();
             SendCountingInfo sci = new SendCountingInfo();
             sci.StartSendCountingInfo();
        }
        catch (Exception exp)
        {
            System.Diagnostics.Debug.WriteLine(exp.Message);
            System.Diagnostics.Debug.WriteLine(exp.Source);
            System.Diagnostics.Debug.WriteLine(exp.StackTrace);
        }
        ResumeLayout(true);
   });
}

你知道怎么了吗?

使用线程查看问题是否持续存在

using System.Threading;
//Put this where you want to start the first timer
Thread thread = new Thread(dowork =>
{
    public void StartSendCountingInfo();
}

如果您正在更新用于控制的GUI

guicontrol.BeginInvoke((MethodInvoker)delegate() 
{ 
    guicontrol.Text = "aa";
    //etc
});

最新更新