不能打SerialDataReceivedEvent?

can not hit the SerialDataReceivedEvent?

所有这些都来自我想在 .Net 中使用 SerialPort class 的想法,但唯一的方法是调用 dll 。因为我只能从调用这个 dll 的程序中获取接口。我的代码在下面。

我写了一篇关于串口的文章class,

public class CommClass
{
    public SerialPort _port;
    private string _receivedText;
    public string receivedText
    {
        get { return _receivedText; }
        set
        {
            _receivedText = value;
        }
    }
    public CommClass(string _pname)
    {
        portList = SerialPort.GetPortNames();
        _port = new SerialPort(portList[0]);
        if (portList.Length < 1)
            _port= null;
        else
        {
            if(portList.Contains(_pname.ToUpper()))
            { 
                _port = new SerialPort(_pname);
                _port.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);
             }
        }
    }
    private  void com_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string indata = _port.ReadExisting();
        receivedText = indata;
    }
}

Bytestoread 我可以看到有 r 数据传入,我可以从端口获取数据。ReadExisting(),但是 receivedText 确实没有改变,它没有命中 SerialDataReceived 事件。是我的方法不对吗?有什么建议吗?谢谢

我从 CommClass 创建了一个 dll,然后在我的 winform 程序中调用它,它有一个按钮和一个文本框。单击按钮,然后我初始化端口

public Form1()
    {
        InitializeComponent();
    }

    public CommClass mycom;
private void button1_Click(object sender, EventArgs e)
    {
       mycom = new CommClass("com3");
       mycom._port.Open();
       textbox.Text=mycom.receivedText;//i add a breakpoint at this line ,
    }

点击它时,我检查mycom._port.PortName是"com3",它的IsOpen()是"Open",我使用虚拟端口发送数据。我发送“1111”,然后检查 mycom._port.BytestoRead 为 4,mycom._port.ReadExisting() 为“1111”,但 mycom.receivedText 为空。我的困惑是我不知道数据何时到来。如何在没有代码“using System.Io.Ports”的情况下在我的 winform 中使用 DataReceived 事件,仅供参考 CommClass.dll。我说清楚了吗?感谢您的帮助。

   mycom._port.Open();
   textbox.Text=mycom.receivedText;//i add a breakpoint at this line ,

该代码无法运行,这是一个线程竞争错误。打开端口后,DataReceived 事件不会立即 触发。这将花费一微秒左右的时间,或多或少。线程池线程必须开始触发事件。当然,设备实际上必须发送一些东西,他们通常只会在你先发送一些东西时才会这样做。

这显然没有发生,您的 DataReceived 事件处理程序也有错误。不允许在该事件中更新控件的 Text 属性,因为它在工作线程上运行。您的程序将以 InvalidOperationException 轰炸。

你必须改为这样写:

private void com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    string indata = _port.ReadExisting();
    this.BeginInvoke(new Action(() => {
         textbox.AppendText(indata);
    }));
}

根据附加规定,您不能保留它,更新 TextBox 的文本 属性 并使其在屏幕上可见是一项昂贵的操作,当设备开始高速传输数据。