C#只读串行口,当数据来源 [英] C# read only Serial port when data comes

查看:125
本文介绍了C#只读串行口,当数据来源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要读我的串行端口,但只有当数据来源(我想没有轮询)。

I want read my serial port but only when data comes(I want not polling).

这是我要做的事。

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

然后我启动一个线程

And then I start a thread

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

在我readCom里我读连续(轮询:()

and in my readCom I'm reading continuous (polling :( )

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);
        }
    }

我要当一个中断来临YOUT读取。但是,我怎么能做到这一点?

I want yout read when a Interrupt is coming. But how can I do that ?

推荐答案

您将有一个事件处理程序添加到DataReceived事件检索。

You will have to add an eventHandler to the DataReceived event.

下面是msdn.microsoft.com一个例子,有些编辑:查看评论

Below is an example from msdn.microsoft.com, with some edits: see comments!:

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将触发您的信息打印到控制台。我想你应该能够做到这一点在你的code。

Everytime data comes in, the DataReceivedHandler will trigger and prints your data to the console. I think you should be able to do this in your code.

这篇关于C#只读串行口,当数据来源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆