SerialPort有时会挂起

问题描述 投票:3回答:2

我正在用C#开发一个.NET 4.0 WPF应用程序,通过RS232控制电机。退出应用程序时我遇到问题,应用程序有时会在关闭comport时死锁。

在互联网上进行一些研究后,我注意到这是一个常见的问题,在DataReceivedEvent中使用BeginInvoke或在不同的线程中关闭serialport应该可以解决问题。这些变通办法的问题在于。 1.我不使用DataReceiveEvent。 2.在另一个线程中关闭serialport没有任何区别。会发生什么是GUI关闭,但您可以在TaskManager中看到该进程仍在运行。

我尝试过的其他事情是:

  • 没有关闭serialport并且只是退出应用程序。这成功关闭了应用程序和进程,但仍然阻止了serialport,并且要解锁我需要重新启动计算机的serialport。
  • 在关闭序列端口之前和之后睡几秒钟。
  • 让应用程序成为WinForms应用程序。而不是WPF。两者之间的僵局没有区别。

我运行该程序的计算机使用安装在主板上并具有Microsoft驱动程序的COM端口。

现在有些代码:

Window_Closing事件如下所示:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    window.Closing -= Window_Closing;            
    Thread CloseDown = new Thread(new ThreadStart(server.Dispose)); //Closes serialport everything in another thread to avoid hang on serialport close.
    CloseDown.Start();
}

其中server是管理serialport的对象。并且Dispose调用serialport close函数。

串口关闭功能:

public void Close()
{
    DebugLog.Write(3, "-->MacCommSerialPort.Close");
    _com.Close();                        
    DebugLog.Write(3, "<--MacCommSerialPort.Close");
}

串口设置:

_com = new SerialPort(portNumber);
_com.BaudRate = 19200;
_com.Parity = Parity.None;
_com.DataBits = 8;
_com.Encoding = Encoding.GetEncoding("Windows-1252");
_com.StopBits = StopBits.One;
_com.RtsEnable = false;
_com.DtrEnable = false;
_com.WriteTimeout = 400;
_com.ReadTimeout = 1000;
c# .net serial-port
2个回答
2
投票

我碰巧看了你的代码并猜测你应该在关闭GUI之前使用AutoThreadRest事件。

private static AutoResetEvent PortClosedEvent = new AutoResetEvent(false);

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) 
    { 
        window.Closing -= Window_Closing;             
        Thread CloseDown = new Thread(new ThreadStart(server.Dispose));
        CloseDown.Start(); 
        PortClosedEvent.WaitOne(); 
    } 

在完成处理连接之后,在server.Dispose方法中添加以下代码行。

PortClosedEvent.Set();

0
投票

我会检查以确保您的应用程序和电机(即发送器和接收器)之间的握手协议匹配。

© www.soinside.com 2019 - 2024. All rights reserved.