System.Timers.Timer Usage

本文关键字:Usage Timer Timers System | 更新日期: 2023-09-27 18:22:29

为了这个问题的目的,我将完整地包含我的一个类:

public class SerialPortConnection
{
    private SerialPort serialPort;
    private string ping;
    double failOut;
    bool isReceiving;
    public SerialPortConnection(string comPort = "Com1", int baud = 9600, System.IO.Ports.Parity parity = System.IO.Ports.Parity.None, int dataBits = 8, System.IO.Ports.StopBits stopBits = System.IO.Ports.StopBits.One, string ping = "*IDN?", double failOut = 2)
    {
        this.ping = ping;
        this.failOut = failOut * 1000;
        try
        {
            serialPort = new SerialPort(comPort, baud, parity, dataBits, stopBits);
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    //Open Serial Connection. Returns False If Unable To Open.
    public bool OpenSerialConnection()
    {
        //Opens Initial Connection:
        try
        {
            serialPort.Open();
            serialPort.Write("REMOTE'r");
        }
        catch (Exception e)
        {
            throw e;
        }
        serialPort.Write(ping + "'r");
        var testReceived = "";
        isReceiving = true;
        Timer StopWatch = new Timer(failOut);
        StopWatch.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        StopWatch.Interval = failOut;
        StopWatch.Enabled = true;
        while (isReceiving == true)
        {
            try
            {
                testReceived += serialPort.ReadExisting();
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        StopWatch.Dispose();
        if (testReceived.Contains('>'))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public string WriteSerialConnection(string SerialCommand)
    {
        try
        {
            serialPort.Write(String.Format(SerialCommand + "'r"));
            var received = "";
            bool isReceiving = true;
            Timer StopWatch = new Timer(failOut);
            StopWatch.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            StopWatch.Interval = failOut;
            StopWatch.Enabled = true;
            while (isReceiving == true)
            {
                try
                {
                    received += serialPort.ReadExisting();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            if (received.Contains('>'))
            {
                return received;
            }
            else
            {
                received = "Error: No Data Received From Device";
                return received;
            }
            StopWatch.Dispose();
        }
        catch (Exception e)
        {
            throw e;
        }        
    }
    //Closes Serial Connection. Returns False If Unable To Close.
    public bool CloseSerialConnection()
    {
        try
        {
            serialPort.Write("LOCAL'r");
            serialPort.Close();
            return true;
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        isReceiving = false;
    }
}

我在这里试图做的是让循环运行一段设定的时间(在这种情况下是两秒),因为连接到我使用的串行端口的设备是不可预测的。我不知道我会从中收到什么数据,也不知道需要多长时间。这是无法解决的,也是我必须解决的问题。目前,我的最佳选择是等待一段时间,然后检查我收到的数据是否有结束令牌(">")。即使在课堂上,我也试过安装计时器:

Timer StopWatch = new Timer(failOut * 1000);
StopWatch.Elapsed += new ElapsedEventHandler(OnTimedEvent);
StopWatch.Interval = failOut;
StopWatch.Enabled = true;

但它似乎不起作用。事件本身看起来是这样的:

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    isReceiving = false;
}

我的目标是切断接收与的联系

(while isReceiving == true)
{
    //Do Something
}

但它似乎不起作用。我想我已经完全误解了计时器的功能,但我以前有过实施它的建议。我做错了什么?如果我只是完全滥用了它,我可以用什么来代替计时器?正如我所说,我别无选择,只能等待一段时间,检查我收到了什么。除了等待和希望我能得到什么之外,这是无法避免或以任何方式处理的。

编辑:

也许我最好澄清一下。OnTimedEvent事件正在激发,变量被设置为false,但由于isReceiving没有被设置为false,因此它不会切断循环。

编辑2:

Mr。帕桑特的回答很好,除非我遇到一个奇怪的错误。由于我不认为这是他的答案中的问题,更可能是硬件缺陷,或者其他奇怪和模糊的东西,我将他的答案标记为已接受。我建议任何选择实施他的答案的人也查看我在这里提交的问题:

C#中明显的IO.Ports.SerialPort缺陷或可能的硬件缺陷

System.Timers.Timer Usage

你把事情搞得太难了。只需将SerialPort.NewLine属性更改为">"即可。并使用SerialPort.ReadLine()读取响应。如果需要,您仍然可以使用超时,分配SerialPort.ReadTimeout属性并准备捕获TimeoutException。