簡體   English   中英

Visual Studio C#使用計時器按住程序1小時

[英]Visual Studio C# using timer to hold down the program for 1 hour

我是一個新用戶,我希望添加一個計時器來按住程序一個小時然后繼續。

這是程序:

  1. 通過serialport發出命令,例如high
  2. 持有一個小時
  3. 再次發出相同的命令'high'
  4. 持有一個小時
  5. 它會重復,直到按下按鈕。

我該如何實現計時器? 因為我嘗試在線搜索並找到了一些例子。 我把它包含在Form1.cs

static System.Timers.Timer Timer1;
void button1_Click(object sender, EventArgs e)
{
     Timer1 = new System.Timers.Timer(60*60*1000);
     Timer1.Elapsed += new ElapsedEventHandler(TimedEvent);
     Timer1.Enabled = true;
}
private void TimedEvent(Object source, ElapsedEventArgs e)
{
     serialPort1.Write("high");
}

即使這段代碼有助於每小時重復一次,但它只在60分鍾后完成TimedEvent。 我需要先寫入serialport然后執行計時器。 如何修改代碼以達到我想要的結果?

編輯:我意識到這個代碼不起作用,因為計時器沒有持續一個小時。 而是將它放在form1_load中工作。

        private void Form1_Load(object sender, EventArgs e)
        {
            Timer1 = new System.Timers.Timer(10*1000); 
            Timer1.Elapsed += TimedEvent;
        }

試過這個(下面),但計時器不起作用

static System.Windows.Forms.Timer timer4 = new System.Windows.Forms.Timer();
void button1_Click(object sender, EventArgs e)
    {
         Writetoserialport();
         timer4.Interval = 10000; // testing on 10second interval
         timer4.Enabled = true;
    }

當我刪除Writetoserialport() ,程序將永遠運行。

第一次運行時直接調用TimedEvent

private void Form1_Load(object sender, EventArgs e)
{
    Timer1 = new System.Timers.Timer(10*1000); 
    Timer1.Elapsed += TimedEvent;
    TimedEvent();
}

但對於每小時發生的事情,Windows服務可能是更好的選擇。

這將有效,但有時因為System.Timers.Timer在ThreadPool線程上觸發TimedEvent而關閉程序時可能會崩潰。 有時可能發生的事情是當程序關閉時,SerialPort對象將被釋放,但由於Timer仍然在另一個線程上執行,它將觸發TimedEvent並嘗試寫入serialPort,但它會使程序崩潰,因為它將被處置。

您應該查看System.Windows.Forms.Timer,它適用於這樣的GUI線程。

// INSTEAD, TRY THIS. 

//現在真的很晚才忘記在從上面復制粘貼后更改一些代碼,現在應該很好。

    static System.Windows.Forms.Timer timer1;
    void button1_Click(object sender, EventArgs e)
    {
             timer1 = new System.Windows.Forms.Timer(60*60*1000);
             timer1.Tick += Timer1_Tick;
             timer1.Enabled = true;
             WriteToSerialPort(); // Call method directly for writing to port.
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
             WriteToSerialPort(); 
    }

    private void WriteToSerialPort()
    {
             serialPort1.Write("high"); // write to port
    }

這是另一個允許您沒有專用方法寫入串行端口的示例。 我想要專用方法,因此可以將串行端口寫入定時器tick事件之外,而不必多次寫入串行端口代碼。 下面的代碼需要在try ... catch塊中。 注意:System.Windows.Forms.Timer在這里。

using System;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;

namespace SerialPortSample
{
    public partial class Form1 : Form
    {
        private Timer timer1 = new Timer { Interval = 1000, Enabled = false }; // initialize timer, with a one second interval and disabled
        private Button startTimerButton = new Button { Name = "startTimerButton",Text = @"Toggle Timer", Size = new Size(130, 33), Location = new Point(0, 0) };

        // This is a place holder for the SerialPort control you probably have on your Form.
        //Remove this instance of serialPort1 and use the serialPort1 control from your form.
        private SerialPort serialPort1 = new SerialPort(); 
        public Form1()
        {
            InitializeComponent();
            // add button to Form
            this.Controls.Add(startTimerButton); // add button to form1
            startTimerButton.Click += StartTimerButton_Click;
            timer1.Tick += Timer1_Tick; // attach timer tick event
        }

        private void StartTimerButton_Click(object sender, EventArgs e)
        {
            timer1.Enabled = !timer1.Enabled; // toggle timer.endabled, if false the Tick event will not be raised
                timer1.Interval = 1000; // set timer interval to 1000 so the next time it is enabled it triggers immediately.
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            timer1.Interval = 60 * 60 * 1000; // set timer interval to 1 hour so it will not trigger for an hour 

            if (!serialPort1.IsOpen)
                serialPort1.Open(); // open serial port if not open

            serialPort1.Write("high"); // write to the serial port

            serialPort1.Close(); // close serial port
        }


    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM