C# Serialport执行close()方法时,程序卡死的解决办法

根据网上搜到的文章,程序中添加两个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()方法时,程序卡死的解决办法

上一篇:2015 UESTC Winter Training #7【2010-2011 Petrozavodsk Winter Training Camp, Saratov State U Contest】


下一篇:WebFlux- WebClient(二)