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描述的比较清楚。

原文地址:https://www.cnblogs.com/soundcode/p/9391792.html