timer1挂起,而其他进程出现在winforms C#中

本文关键字:winforms 进程 挂起 其他 timer1 | 更新日期: 2023-09-27 18:23:42

我使用间隔为1毫秒的计时器1在文本框中生成时间(小时、分钟、秒、毫秒)。

现在,每当我连续收到值时。我将不得不串行写入数据,这将使3个led打开,每个之间有1秒的延迟。我正在使用文本框来显示类似Output 1 ON&CCD_ 2随时间变化。这样我就可以真正知道他们什么时候打开。

但问题是,当led打开时,计时器在那一刻挂起,因此不会显示led打开的确切时间。

我的应用程序需要显示每个led打开的时间。

代码:(计时器)

private void timer1_Tick(object sender, EventArgs e) 
{
 dateTime = DateTime.Now;
 time = dateTime.Hour + ":" + dateTime.Minute + ":" + dateTime.Second + ":" + dateTime.Millisecond;
 date = Convert.ToString(dateTime.Day + "/" + dateTime.Month + "/" + dateTime.Year);
 textBox2.Text = time;
 textBox1.Text = date;
}

代码:(串行发送/接收)

String data = serialPort1.ReadLine();
if (data == "11")
{
   textBox4.AppendText(time + " Input 1 HIGH'n");
   textBox4.AppendText("'n");
   button11.BackColor = Color.Yellow;
    Thread.Sleep(1000);
    serialPort1.WriteLine("1");
    textBox4.AppendText(time + " Output 1 HIGH'n");
     Thread.Sleep(1000);
     serialPort1.WriteLine("2");
     textBox4.AppendText(time + " Output 2 HIGH'n");
      Thread.Sleep(1000);
      serialPort1.WriteLine("3");
      textBox4.AppendText(time + " Output 2 HIGH'n");
  }

我是winforms的新手,所以不知道。但我已经准备好学习了。我可以用什么让我的计时器在打开led的时不会挂起

timer1挂起,而其他进程出现在winforms C#中

您应该在单独的线程中执行串行传输/接收代码。目前,你的整个应用程序运行在一个线程中,所以当你调用thread.Sleep()时,你的所有应用程序都挂起了,因为每个控件都在等待thread.Sleep结束。

Concider为您的应用程序使用某种多线程方法。例如,在简单的实现中,您可以查看BackgroundWorker类:http://www.codeproject.com/Articles/99143/BackgroundWorker-Class-Sample-for-Beginners