gpt4 book ai didi

c# - 带有 SerialPort 的 Windows 窗体 - 应用程序在关闭窗体后挂起

转载 作者:太空宇宙 更新时间:2023-11-03 11:57:56 26 4
gpt4 key购买 nike

我有一个 Windows 窗体应用程序以连接到 Arduino 开发板。当我想关闭它时,它会保持打开状态,直到我停止 Debug模式。当我在 Visual Studio 中运行程序并且单独运行 exe 文件时,会发生这种情况,我必须从任务管理器中停止它。

我尝试了 FormClosingFormClosed 事件,但结果是一样的。我唯一想到的是,出现此问题是因为我在 SerialPortDataRecieved 事件中为我的控件使用了许多 Invoke 函数。我这样做是因为我需要对表单控件进行线程安全调用。这是我的部分代码:

private void spArduino_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (spArduino.BytesToRead > 0)
{
string data = spArduino.ReadLine().Replace("\r", "");
if (data.StartsWith("CUR_TEMP:"))
{
if (lbTemprature.InvokeRequired)
{
lbTemprature.Invoke(new MethodInvoker(delegate {
lbTemprature.Text = "Room temprature " + data.Remove(0,9) + "°C";
}));
}
}
}
}
///////
private void Monitoring_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
spArduino.WriteLine("CLEAR");
spArduino.Close();
}
catch (Exception)
{
MessageBox.Show("errorclose");
}
}

这会出现在我的输出中 (Visual Studio)

The thread 0x2bf0 has exited with code 0 (0x0).
The thread 0x5f24 has exited with code 0 (0x0).
The thread 0x46c4 has exited with code 0 (0x0).
The thread 0x5df4 has exited with code 0 (0x0).
The thread 0x294c has exited with code 0 (0x0).
The thread 0x4620 has exited with code 0 (0x0).
The thread 0x720 has exited with code 0 (0x0).
The thread 0x35a0 has exited with code 0 (0x0).

它一直保持这种状态,直到我停止程序。

谁能帮助我了解我的问题出在哪里以及如何解决?

最佳答案

SerialPort.DataReceived 事件在与主 UI 线程不同的线程上触发,这就是为什么在更新 UI 时需要调用 lbTemprature.Invoke 方法的原因。

关闭窗体而不关闭端口

如果不关闭端口就关闭窗体,那么在关闭窗体时,可能会在窗体释放后触发DataReceived事件,这会在尝试更新UI时引发异常。

关闭窗体前关闭端口

如果您在关闭表单之前关闭端口(例如在 FormClosing 事件中),那么您可能会遇到死锁,因为 SerialPort.Close() 在主 UI 线程等待触发 DataReceived 事件的线程完成事件,DataReceived 事件在调用 lbTemprature 时等待 UI 线程。调用。这可能是导致表单卡住的原因。

解决方案

一种解决方案是调用 lbTemprature.BeginInvoke 来避免死锁。这可能还不够,因为 BeginInvoke 仍然可以在处理表单并引起期望后运行。可能需要向 Form.IsDisposed 属性添加检查。

if (lbTemprature.InvokeRequired)
{
lbTemprature.BeginInvoke(new MethodInvoker(delegate
{
if (!this.IsDisposed)
{
lbTemprature.Text = "Room temprature " + data.Remove(0,9) + "°C";
}
}));
}

关于c# - 带有 SerialPort 的 Windows 窗体 - 应用程序在关闭窗体后挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58752811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com