【问题标题】:Windows form stopwatch elapsed timeWindows 窗体秒表经过时间
【发布时间】:2020-12-22 09:33:24
【问题描述】:

我的窗体应用程序的任务是在时间等于 10 秒时调用方法和 checkBox1_CheckedChanged 事件。但是程序不能去 if 语句做某事。

计时器:

private void timerAU_Tick(object sender, EventArgs e)
    {
        stopwatch.Start();
        time = stopwatch.Elapsed.ToString(@"hh\:mm\:ss\.f");
        TimerAutoUpdateHelper();

        if (time.Equals("00:00:10.1"))
        {
            stopwatch.Reset();
            timerAU.Stop();

            thread.Join();
            thread.Abort();
            MessageBox.Show("OK!");
            checkBox1_CheckedChanged(sender, e);               
        }
    }

复选框:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

            if (checkBox1.Checked == true)
            {
                
                timerAU.Start();
                stopwatch.Start();
                

                thread = new Thread(() => DataProcess.DataFromPLC(new Form1()));
                thread.Start();

                Log.WriteLogFile(EventCategory.AUTOUPDATECHECKED);
            }
            else
            {
                stopwatch.Stop();
                MessageBox.Show(time);
                checkBox1.Checked = false;
                timerAU.Stop();

                thread.Join();
                thread.Abort();

                Log.WriteLogFile(EventCategory.AUTOUPDATEUNCHECKED);
            }
        }

【问题讨论】:

  • thread.Abort(); oh mamma mia, mamma mia .... 永远不要使用它。为了帮助您解决问题,需要更多上下文。那是什么样的计时器? TimerAutoUpdateHelper 做什么? ...
  • 秒表也是定时器控件吗?
  • TimerAutoUpdateHelper 方法包​​含这个从 PLC 查询数据的调用方法。
  • 哪个If语句不能通过?在timerAU_TickcheckBox1_CheckedChanged 内?
  • 嗯,问题是:你做这件事的方式,它永远不会是你所期望的价值。另一件事是:只有当它是确切值时,条件才会为真。不是 10.2 不是 15.7 ,正好是 10.1。所以你可能想要if( stopwatch.Elapsed > TimeSpan.FromSeconds(10) )

标签: c# visual-studio winforms visual-studio-2017


【解决方案1】:

解决了我的问题。我更改了 if 语句并运行成功! :)

if (stopwatch.Elapsed > TimeSpan.FromSeconds(10))
            {
                stopwatch.Reset();
                timerAU.Stop();

                thread.Join();
                
                MessageBox.Show("OK!");
                checkBox1_CheckedChanged(sender, e);               
            }

【讨论】:

  • 你确定吗?您仍在使用线程,仍在使用秒表来测量时间,在等待线程完成时仍处于阻塞状态。该线程正在构建一个新表单,这几乎可以保证出现异常。如果你想在不阻塞的情况下更新 UI,你可以简单地使用 Process<> 类。如果您想在后台运行长时间运行的操作,您可以使用 await Thread.Run() - 仅此一项就无需计时器和秒表。
  • Panagiotis Kanavos 指的是Progress<T> 类(和Task.Run())。顺便说一句,您在此处和问题中的代码在 WinForms 中是无意义的。
猜你喜欢
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 2013-06-19
相关资源
最近更新 更多