C#串口攻击,应用程序在一段时间后崩溃

时间:2012-06-04 04:28:31

标签: c#

我正在编写一个从COM端口读取数据并在屏幕上显示的程序。当数据读取频率较低时,它可以完美地运行并且可以全天运行。但是,当数据每秒发送一次时,程序每30分钟崩溃一次。错误代码是c0000005访问冲突。

     void Start()
     {
     _serialPort = new SerialPort(TempPortName, 9600, Parity.None, 8, StopBits.One);        
    _serialPort.Handshake = Handshake.None;
     _serialPort.ReadTimeout = 1000;
     _serialPort.ReadBufferSize = 100000;
    readThread = new Thread(Read);
     readThread.Start();        
     }

void Read()
    {
    string MessageSection = "";
    char[] end = {'\r'};    

    //string MessageSection = "";
    while (readData)
    {           
    Thread.Sleep(10);
        if (_serialPort.IsOpen)
        {

            string message = "test"; 

         try
                {
                    message = ((char)(_serialPort.ReadByte())).ToString();

                }
                catch
                {
                    message = "";
                }

                if (message != "")
                {

                    message = MessageSection + message; 

                    string[] MessageArray = message.Split(end);
                    if (!message.EndsWith("\r"))
                    {
                        MessageSection = MessageArray[MessageArray.Length - 1];                    
                    }
                    else
                    {
        if(message.Length>0)
        {
            doSomething();
        }
                        MessageSection = "";
                    }
                }
        else {
        }

        }
        else
        {
            try
            {
                _serialPort.Open();

            }

            catch
            {
                print("Error"); 
            }
        }
    }

    }

我正在使用Unity 3D,它是关于buffersize吗?

1 个答案:

答案 0 :(得分:1)

使用while loop进行串行端口通信并不是一种不错的方式。您注册SerialPort.DataReceived Event以接收端口上的入站数据。

以下是MSDN的示例代码

using System;
using System.IO.Ports;

class PortDataReceived
{
    public static void Main()
    {
        SerialPort mySerialPort = new SerialPort("COM1");

        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    private static void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.WriteLine("Data Received:");
        Console.Write(indata);
    }
}