標籤:
根據網上搜到的文章,程式中添加兩個bool變數,作為狀態標記,保證串口關閉時,串口事件已處理完
private volatile bool is_serial_listening = false;//串口正在監聽標記
private volatile bool is_serial_closing = false;//串口正在關閉標記
//Program Begins
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports; //使用Serialport需要用到這個namespace
namespace commtest
{
public partial class Form1 : Form
{
private string DispString; //used to store the values read
private volatile bool is_serial_listening = false;//串口正在監聽標記
private volatile bool is_serial_closing = false;//串口正在關閉標記
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Port name can be identified by checking the ports
// section in Device Manager after connecting your device
serialPort1.PortName = "COM3";
//Provide the name of port to which device is connected
//default values of hardware[check with device specification document]
serialPort1.BaudRate = 9600;
serialPort1.Parity = Parity.None;
serialPort1.StopBits = StopBits.One;
serialPort1.Handshake = Handshake.None;
serialPort1.Open(); //opens the port
serialPort1.ReadTimeout = 200;
if (serialPort1.IsOpen)
{
DispString = "";
//txtCardKeyDeactivate.Text = "";
}
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (is_serial_closing)
{
is_serial_listening = false; //準備關閉串口時,reset串口偵聽標記
return;
}
try
{
if (serialPort1.IsOpen)
{
is_serial_listening = true;
DispString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
Byte[] BSendTemp = new Byte[1];
BSendTemp[0] = 0x00;
serialPort1.Write(BSendTemp, 0, 1);
}
}
finally
{
is_serial_listening = false;//串口調用完畢後,reset串口偵聽標記
}
}
private void DisplayText(object sender, EventArgs e)
{
textBox1.AppendText(DispString);
textBox2.Text = SubstringCount(textBox1.Text, "ok").ToString();//自己寫的測試語句,統計"ok"字串出現的次數
}
private static int SubstringCount(string str, string substring)
{
if (str.Contains(substring))
{
string strReplaced = str.Replace(substring, "");
return (str.Length - strReplaced.Length) / substring.Length;
}
return 0;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
is_serial_closing = true;//關閉視窗時,置位is_serial_closing標記
while (is_serial_listening) Application.DoEvents();
serialPort1.Close();
}
}
}
C# Serialport執行close()方法時,程式卡死的解決辦法