private void btnStart_Click(object sender, EventArgs e)
{
// 设置串口参数
serialPort1.PortName = "COM4"; // 请根据实际情况设置为您的串口号
serialPort1.BaudRate = 4800; // 设置波特率
serialPort1.Parity = Parity.None;
serialPort1.StopBits = StopBits.One;
serialPort1.DataBits = 8;
serialPort1.Handshake = Handshake.None;
// 若串口未打开则开启串口并启动接收数据任务
if (!serialPort1.IsOpen)
{
serialPort1.Open();
cancellationTokenSource = new CancellationTokenSource();
StartReceivingDataAsync(cancellationTokenSource.Token);
label1.Text = "已连接";
}
}
private void btnStop_Click(object sender, EventArgs e)
{
// 若串口已打开则关闭串口并取消接收数据任务
if (serialPort1.IsOpen)
{
cancellationTokenSource.Cancel();
serialPort1.Close();
label1.Text = "连接断开";
}
}
private async void StartReceivingDataAsync(CancellationToken token)
{
try
{
await Task.Run(() => ReceiveData(token), token);
}
catch (OperationCanceledException)
{
// 当任务取消时,可以在这里进行一些清理工作
}
}
private void ReceiveData(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
if (serialPort1.BytesToRead > 0)
{
try
{
// 读取串口接收到的字节数组
byte[] receivedBytes = new byte[serialPort1.BytesToRead];
serialPort1.Read(receivedBytes, 0, receivedBytes.Length);
// 将接收到的字节数组转换为字符串(这里假设是以ASCII编码发送的数字)
string data = System.Text.Encoding.ASCII.GetString(receivedBytes);
// 在这里处理接收到的数据,调用Invoke方法在UI线程中更新界面
this.Invoke((MethodInvoker)delegate
{
textBoxReceivedData.AppendText(data.TrimEnd('\0') + Environment.NewLine);
});
}
catch (Exception ex)
{
// 发生错误时可以记录日志或显示消息
}
}
else
{
// 如果没有数据可读,可以让线程短暂休眠以减小CPU使用率
Thread.Sleep(100);
}
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
// 若窗体正在关闭时,确保取消接收数据任务并关闭串口
cancellationTokenSource?.Cancel();
if (serialPort1.IsOpen)
{
serialPort1.Close();
}
base.OnFormClosing(e);
}
10-25
2002
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-19
06-03
2171
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-01