简体   繁体   English

.NET SerialPort DataReceived事件未触发

[英].NET SerialPort DataReceived event not firing

I have a WPF test app for evaluating event-based serial port communication (vs. polling the serial port). 我有一个WPF测试应用程序,用于评估基于事件的串行端口通信(与轮询串行端口)。 The problem is that the DataReceived event doesn't seem to be firing at all. 问题是DataReceived事件似乎根本没有触发。

I have a very basic WPF form with a TextBox for user input, a TextBlock for output, and a button to write the input to the serial port. 我有一个非常基本的WPF表单,其中包含用于用户输入的TextBox,用于输出的TextBlock以及用于将输入写入串行端口的按钮。

Here's the code: 这是代码:

public partial class Window1 : Window
{
    SerialPort port;

    public Window1()
    {
        InitializeComponent();

        port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
        port.DataReceived +=
            new SerialDataReceivedEventHandler(port_DataReceived);  
        port.Open();
    }

    void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        Debug.Print("receiving!");
        string data = port.ReadExisting();
        Debug.Print(data);
        outputText.Text = data;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Debug.Print("sending: " + inputText.Text);
        port.WriteLine(inputText.Text);
    }
}

Now, here are the complicating factors: 现在,以下是复杂因素:

  1. The laptop I'm working on has no serial ports, so I'm using a piece of software called Virtual Serial Port Emulator to setup a COM2. 我正在处理的笔记本电脑没有串口,因此我使用一个名为Virtual Serial Port Emulator的软件来设置COM2。 VSPE has worked admirably in the past, and it's not clear why it would only malfunction with .NET's SerialPort class, but I mention it just in case. VSPE过去曾经令人钦佩地工作,并且不清楚为什么它只会出现.NET的SerialPort类故障,但我提到它以防万一。

  2. When I hit the button on my form to send the data, my Hyperterminal window (connected on COM2) shows that the data is getting through. 当我点击表单上的按钮发送数据时,我的超级终端窗口(连接在COM2上)显示数据正在通过。 Yes, I disconnect Hyperterminal when I want to test my form's ability to read the port. 是的,当我想测试我的表单读取端口的能力时,我断开Hyperterminal的连接。

  3. I've tried opening the port before wiring up the event. 在尝试连接事件之前,我尝试打开端口。 No change. 没变。

I've read through another post here where someone else is having a similar problem. 我已经阅读了另一篇文章,其中有人遇到了类似的问题。 None of that info has helped me in this case. 在这种情况下,这些信息都没有帮助我。

EDIT: 编辑:

Here's the console version (modified from http://mark.michaelis.net/Blog/TheBasicsOfSystemIOPortsSerialPort.aspx ): 这是控制台版本(从http://mark.michaelis.net/Blog/TheBasicsOfSystemIOPortsSerialPort.aspx修改):

class Program
{
    static SerialPort port;

    static void Main(string[] args)
    {
        port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
        port.DataReceived +=
            new SerialDataReceivedEventHandler(port_DataReceived);
        port.Open();

        string text;
        do
        {
            text = Console.ReadLine();
            port.Write(text + "\r\n");
        }
        while (text.ToLower() != "q");
    }

    public static void port_DataReceived(object sender,
        SerialDataReceivedEventArgs args)
    {
        string text = port.ReadExisting();
        Console.WriteLine("received: " + text);
    }
}

This should eliminate any concern that it's a Threading issue (I think). 这应该消除任何担心这是一个线程问题(我认为)。 This doesn't work either. 这也不起作用。 Again, Hyperterminal reports the data sent through the port, but the console app doesn't seem to fire the DataReceived event. 同样,Hyperterminal报告通过端口发送的数据,但控制台应用程序似乎没有触发DataReceived事件。

EDIT #2: 编辑#2:

I realized that I had two separate apps that should both send and receive from the serial port, so I decided to try running them simultaneously... 我意识到我有两个独立的应用程序,应该从串口发送和接收,所以我决定尝试同时运行它们...

If I type into the console app, the WPF app DataReceived event fires, with the expected threading error (which I know how to deal with). 如果我输入控制台应用程序,WPF应用程序DataReceived事件将触发,并出现预期的线程错误(我知道如何处理)。

If I type into the WPF app, the console app DataReceived event fires, and it echoes the data. 如果我输入WPF应用程序,控制台应用程序DataReceived事件将触发,并且它会回显数据。

I'm guessing the issue is somewhere in my use of the VSPE software, which is set up to treat one serial port as both input and output. 我猜这个问题出在我使用VSPE软件的某个地方,该软件设置为将一个串口视为输入和输出。 And through some weirdness of the SerialPort class, one instance of a serial port can't be both the sender and receiver. 通过SerialPort类的一些奇怪,串行端口的一个实例不能同时是发送方和接收方。 Anyway, I think it's solved. 无论如何,我认为它已经解决了。

port.DtrEnable = true;

这解决了它,我没有启用DataTransmitReady标志,因此没有收到任何数据。

I can't say for sure, but there could be a threading issue. 我不能肯定地说,但可能存在线程问题。 WPF handles threading differently, and the polling of the virtual port is asynchronous, I believe. WPF以不同的方式处理线程,我相信虚拟端口的轮询是异步的。 Have you tried this with a Windows Forms or console application to prove that it can work at all? 您是否尝试使用Windows窗体或控制台应用程序来证明它可以工作?

I use the exact same setup, it works perfectly now but had to solve many many problems to get there. 我使用完全相同的设置,它现在完美地工作,但必须解决很多问题才能到达那里。

Here is why my initial declaration looks like: 这就是为什么我的初始声明如下:

comControl = new SerialPort();

//This is important - determine your min nb of bytes at which you will fire your event, mine is 9
comControl.ReceivedBytesThreshold = 9; 

//register the event handlers
comControl.DataReceived += new SerialDataReceivedEventHandler(OnReceive);
comControl.PinChanged += new SerialPinChangedEventHandler(OnPinChanged);

I seperated the open port and close port methods since i often check if the com port has been closed. 我分开了开放端口和关闭端口方法,因为我经常检查com端口是否已经关闭。

public bool OpenPort()
{
    try
    {
        //must keep it open to maintain connection (CTS)
        if (!comControl.IsOpen)
        {
             comControl.Open();
             comControl.RtsEnable = true;
        }
    }
    catch (Exception e)
    {
        //error handling here
    }
}

Lastly, verify that your Virtual Com Port driver is installed properly and that you are using the right port, a plug and play for my adapter was not enough. 最后,验证您的Virtual Com Port驱动程序是否已正确安装并且您使用的是正确的端口,我的适配器的即插即用是不够的。 If you want to create a sort of control that will allow you to pick the ports available at runtime, the following command will give you the available ports: 如果要创建一种允许您在运行时选择可用端口的控件,以下命令将为您提供可用端口:

System.IO.Ports.SerialPort.GetPortNames()

I have had similar issue when running such a driver from a Form, as well, though no VSPE just a plain SP. 从Form中运行这样的驱动程序时也有类似的问题,尽管没有VSPE只是一个普通的SP。 Believe this was a STA-model issue as moving to including it in a console app fixed enough. 相信这是一个STA模型问题,因为它将其包含在足够固定的控制台应用程序中。

I use VSPE too! 我也用VSPE! It does work wonderfully.. I was having this same problem and the way I fixed it was to make the two com ports a PAIR in VSPE instead of just creating two virtual com ports 它运行得非常好..我遇到了同样的问题,我修复它的方法是在VSPE中使两个COM端口成为PAIR而不是仅创建两个虚拟COM端口

I ran into a similarly odd problem recently, but only on some machines. 我最近遇到了一个同样奇怪的问题,但只在某些机器上。 As Dave Swersky noted, this may have been a threading issue, especially if you were running under .NET 4.0 or later. 正如Dave Swersky所说,这可能是一个线程问题,特别是如果你在.NET 4.0或更高版本下运行。

In .NET 4.0 the event handler is triggered on a ThreadPool thread, and under certain circumstances there may be a substantial delay before that occurs. 在.NET 4.0中,事件处理程序在ThreadPool线程上触发,在某些情况下,在此之前可能会有很长的延迟。 (In my code, which had been working perfectly under .NET 2.0, problems were observed as soon as we upgraded to .NET 4.5. The event handler would often be triggered much later than would be expected, and sometimes it would not get triggered at all!) (在我的代码中,一直在.NET 2.0下完美运行,一旦我们升级到.NET 4.5就会出现问题。事件处理程序通常会比预期的更晚触发,有时它不会被触发所有!)

Calling ThreadPool.SetMinThreads(...) with a bigger value for the completion threads made the issue disappear as quickly as it had arrived. 调用具有更大值的ThreadPool.SetMinThreads(...)完成线程使得问题尽快消失。 In the context of our application ThreadPool.SetMinThreads(2, 4) was sufficient. 在我们的应用程序的上下文中, ThreadPool.SetMinThreads(2, 4)就足够了。 On the machines where the problem was observed, the default values (as obtained by calling ThreadPool.SetMinThreads ) were both 2. 在观察到问题的机器上,默认值(通过调用ThreadPool.SetMinThreads获得)都是2。

I can only surmise that the problem was indeed with the Virtual Serial Port Emulator program. 我只能推测问题确实存在于虚拟串口仿真器程序中。 this is NOT to say there is a problem with that software: VSPE has worked very well for me so far. 这并不是说该软件存在问题:到目前为止,VSPE对我来说效果很好。 But there was some conflict between my code and how I had set up the VSPE connector. 但是我的代码和我如何设置VSPE连接器之间存在一些冲突。

Two days ago I had the same problem and it was a big headache because I needed to deliver the app today. 两天前我遇到了同样的问题,这是一个非常令人头痛的问题,因为我今天需要提供应用程序。 So.. after too much googleashion I supposed that the issue was another thing and not my code. 所以..经过太多googleashion后我认为问题是另一回事,而不是我的代码。

My solution was uninstall McAfee antivirus and all things related with this. 我的解决方案是卸载McAfee防病毒以及与此相关的所有事情。 When I saw the logs of McAfee it had records about stop threads and I assumed that the SerialDataReceivedEventHandler() run in a thread. 当我看到McAfee的日志时,它有关于停止线程的记录,我假设SerialDataReceivedEventHandler()在一个线程中运行。

I hope this solution works for you. 我希望这个解决方案适合你。 Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用DataReceived事件在.Net中使用SerialPort? - How to use SerialPort in .Net by using DataReceived event? .Net SerialPort Readline与DataReceived事件处理程序 - .Net SerialPort Readline Vs DataReceived Event Handler .NET SerialPort DataReceived 事件线程干扰主线程 - .NET SerialPort DataReceived event thread interference with main thread SerialPort 在关闭后触发 DataReceived 事件 - SerialPort fires DataReceived event after close .NET CORE(在Windows上),DataReceived称为一个串行端口的频率,该频率由其他串行端口影响 - .NET CORE(on windows), DataReceived called frequency of one serialPort effected by other serialPort 我期望LibUsbDotNet USBEndpointReader DataReceived事件未触发 - LibUsbDotNet USBEndpointReader DataReceived event is not firing when I expect it to 为什么调制解调器处于DATA模式时不会触发System.IO.Ports.SerialPort.DataReceived事件? - Why System.IO.Ports.SerialPort.DataReceived event doesn't fire when modem is in DATA mode? NetworkStream,是否有类似于SerialPort的DataReceived? (C#) - NetworkStream, is there something similar to DataReceived for a SerialPort? (C#) SerialPort.DataReceived在Windows服务/会话零中不起作用 - SerialPort.DataReceived doesn't work in Windows Service / Session Zero C#.Net Serial DataReceived对于高速率数据,事件响应太慢 - C# .Net Serial DataReceived Event response too slow for high-rate data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM