3

我正在编写一个从 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,它与缓冲区大小有关吗?

4

1 回答 1

1

这不是您使用while loop. 您正在注册SerialPort.DataReceived事件以接收端口上的传入数据。

这是来自 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);
    }
}
于 2012-06-04T04:44:07.557 回答