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描述的比較清楚。
總結
以上是生活随笔為你收集整理的c# SerialPort会出现“已关闭 Safe handle”的错误的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 工商银行9位营销代码是什么 用来统计员工
- 下一篇: 控股51%和67%区别