C# Serialport執行close()方法時,程式卡死的解決辦法

來源:互聯網
上載者:User

標籤:

根據網上搜到的文章,程式中添加兩個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()方法時,程式卡死的解決辦法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.