8

我想读取我的串行端口,但只有在数据到来时(我不想轮询)。

我就是这样做的。

                Schnittstelle = new SerialPort("COM3");
                Schnittstelle.BaudRate = 115200;
                Schnittstelle.DataBits = 8;
                Schnittstelle.StopBits = StopBits.Two;
             ....

然后我开始一个线程

             beginn = new Thread(readCom);
             beginn.Start();

在我的 readCom 中,我正在连续阅读(轮询 :( )

private void readCom()
    {

        try
        {
            while (Schnittstelle.IsOpen)
            {

                Dispatcher.BeginInvoke(new Action(() =>
                {

                    ComWindow.txtbCom.Text = ComWindow.txtbCom.Text + Environment.NewLine + Schnittstelle.ReadExisting();
                    ComWindow.txtbCom.ScrollToEnd();
                }));

                beginn.Join(10);

            }
        }
        catch (ThreadAbortException) 
        {

        }

        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

我希望你在中断到来时阅读。但我该怎么做呢?

4

2 回答 2

36

您必须将 eventHandler 添加到 DataReceived 事件。

以下是来自 msdn.microsoft.com 的示例,并进行了一些编辑:请参阅评论!:

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();
    Debug.Print("Data Received:");
    Debug.Print(indata);
}

每次数据进入时,DataReceivedHandler 都会触发并将您的数据打印到控制台。我认为你应该能够在你的代码中做到这一点。

于 2013-04-25T13:14:31.573 回答
5

您需要在打开端口之前订阅 DataReceived 事件,然后在触发时监听该事件。

    private void OpenSerialPort()
    {
        try
        {
            m_serialPort.DataReceived += SerialPortDataReceived;
            m_serialPort.Open();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message + ex.StackTrace);
        }
    } 

    private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        var serialPort = (SerialPort)sender;
        var data = serialPort.ReadExisting();
        ProcessData(data);
    }

串行,当缓冲区中有数据时,触发数据接收事件,这并不意味着您一次获得了所有数据。您可能需要等待多次才能获取所有数据;这是您需要单独处理接收到的数据的地方,也许在您进行最终处理之前将它们保存在某个地方的缓存中。

于 2013-04-25T13:27:19.267 回答