c# SerialPort會出現“已關閉 Safe handle”的錯誤


c# SerialPort使用時出現“已關閉 Safe handle”的錯誤
我在開發SerialPort程序時出現了一個問題,在一段特殊的掃描代碼的時候會出現“已關閉 Safe handle”的錯誤,很疑惑。我是通過線程對串口進行掃描的,原本我以為handle是指的線程,於是代碼跟蹤了半天,但也沒發現線程有什么問題。於是把目光轉移到SerialPort類上,寫了一段測試代碼:

using System;
using System.Threading;
using System.IO.Ports;

namespace ConsoleApplication1
{
    class Program
    {
        static SerialPort com = new SerialPort("COM1", 19200, Parity.Space, 8, StopBits.One);
        static void Main(string[] args)
        {
            com.Open();

            Thread thread = new Thread(new ThreadStart(Run));
            thread.IsBackground = true;
            thread.Start();

            Thread.Sleep(3000);
            thread.Abort();

            Console.WriteLine("Finished!");
            Console.Read();
        }

        static void Run()
        {
            string s = com.ReadLine();

        }
    }
}
果然問題再現了,當thread.Abort()時出現了“已關閉 Safe handle”的錯誤,看來元凶就是SerialPort類了。其實這里不要勿以為是線程關閉出現了錯誤,而是線程里的 string s = com.ReadLine();

SerialPort.ReadLine()在沒有讀取到數據時是會掛起的,這里線程就被掛起了。理應掛起的線程也可以關閉,可是這里SerialPort有點特殊,仍然會讀取串口,而此時開啟的串口資源應該是被GC掉了,或者其他什么的,我沒有細究下去,反正是無法訪問到了。再用com.ReadLine(),當然要發生Handle關閉的情況,於是改寫測試代碼:

using System;
using System.Threading;
using System.IO.Ports;

namespace ConsoleApplication1
{
    class Program
    {
        static SerialPort com = new SerialPort("COM1", 19200, Parity.Space, 8, StopBits.One);
        static void Main(string[] args)
        {
            com.Open();

            Thread thread = new Thread(new ThreadStart(Run));
            thread.IsBackground = true;
            thread.Start();

            Thread.Sleep(3000);
            com.Close();
            thread.Abort();

            Console.WriteLine("Finished!");
            Console.Read();
        }

        static void Run()
        {
            string s = com.ReadLine();
        }
    }
}
加上一段串口關閉的指令,不再讀取handle了,強行關閉(總覺得有點怪)。當然如果后面還要用到串口還得要打開一次,但是問題大體描述就是這樣了。

其實這種方法不是最佳的解決途徑,應該使用到SafeHandle,msdn描述的比較清楚。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM