虚拟串口服务器导致蓝屏,c# 串口监听程序造成死机蓝屏问题

开发者分享在Windows Form应用中使用SerialPort监听串口数据时遇到的问题,程序初次运行和暂停正常,但在从暂停到监听切换时导致系统蓝屏。寻求解决串口通信与界面交互可能存在的冲突和异常处理建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我写了一个小程序用于监听串口的数据,第一次点监听,然后暂停,都还正常,但是再点监听的时候就会造成蓝屏死机.我是在虚拟机里面用SerialNull 模拟的串口通信,用别的测试软件通信正常.串口消息是用测试软件发的,监听正常,但是就是在暂停和监听切换的时候会造成蓝屏死机。请大家帮帮忙看看问题在哪里。

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO.Ports;

using System.Threading;

namespace PortTest

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private SerialPort Sp = new SerialPort();

public delegate void SetTextCallback(string text);

private Thread newThread = null;

string readstr = null;

private void SetText(string text)

{

if (this.textBox_data.InvokeRequired)

{

SetTextCallback d = new SetTextCallback(SetText);

this.Invoke(d, new object[] { text });

}

else

{

this.textBox_data.Text = text;

}

}

private void ThreadProcSafe()

{

this.SetText(readstr);

}

public void Sp_DataReceived(object sender,System.IO.Ports.SerialDataReceivedEventArgs e)

{

byte[] readBuffer = new byte[Sp.ReadBufferSize];

Sp.Read(readBuffer, 0, readBuffer.Length);

readstr =Encoding.UTF8.GetString(readBuffer);

this.newThread = new Thread(new ThreadStart(this.ThreadProcSafe));

this.newThread.Start();

}

private void button1_Click(object sender, EventArgs e)

{

Sp.PortName = "COM4";

Sp.BaudRate = 9600;

Sp.Parity = Parity.None;

Sp.StopBits = StopBits.One;

Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived);

Sp.ReceivedBytesThreshold = 1;

try

{

Sp.Open();

button_pause.Enabled = true;

button_listen.Enabled = false;

}

catch

{

MessageBox.Show("端口COM4打开失败!");

}

}

private void button2_Click(object sender, EventArgs e)

{

newThread.Abort();

Sp.Close();

button_listen.Enabled = true;

button_pause.Enabled = false;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值