最近在做一個有關(guān)高鐵模擬倉顯示系統(tǒng)的客戶端程序,在這個程序中要運用串口serialPort傳輸數(shù)據(jù),因為每次接收數(shù)據(jù)結(jié)束后要更新UI界面,所以就用到了的Invoke,將更新UI的程序代碼封裝到一個方法中,然后通過Incoke調(diào)用,程序跑起來沒有任何問題,但是當你執(zhí)行serialPort.close()是程序就會發(fā)生死鎖,整個程序卡在那里動都動不了。
上網(wǎng)查了很多資料,有各種這樣的說法,有的說定義一個接收數(shù)據(jù)的標志,如果在執(zhí)行關(guān)閉程序是進行判斷,如果數(shù)據(jù)接收完了就關(guān)閉串口,沒有的話繼續(xù)執(zhí)行,但是經(jīng)過親自測試并沒有什么卵用,最后自己研究invoke的時候發(fā)現(xiàn)還有Begininvoke,同時也發(fā)現(xiàn)了他們之間的不同,begininvoke用于后臺更新UI數(shù)據(jù)無需等待的情況,而invoke用于后臺更新UI數(shù)據(jù)無需要等待的情況,弄明白這兩個之間的不同之后才明白原來執(zhí)行serialPort.close()發(fā)生死鎖的原因就是invoke在作祟,改成begininvoke就不會出現(xiàn)死鎖問題。
直接上代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
SerialPort serialPort1 = new SerialPort(“COM5”, 115200, Parity.None, 8, StopBits.One); //初始化串口設(shè)置 //定義委托 public delegate void Displaydelegate(byte[] InputBuf); Byte[] OutputBuf = new Byte[8]; public Displaydelegate disp_delegate; //接收數(shù)據(jù)委托 disp_delegate = new Displaydelegate(DispUI); serialPort1.DataReceived += new SerialDataReceivedEventHandler(Comm_DataReceived); //串口讀取數(shù)據(jù)處理函數(shù) public void Comm_DataReceived(object sender, SerialDataReceivedEventArgs e) { Byte[] InputBuf = new Byte[8]; try { serialPort1.Read(InputBuf, 0,6); //讀取緩沖區(qū)的數(shù)據(jù),每次讀取6個字節(jié)的數(shù)據(jù) System.Threading.Thread.Sleep(100); this.BeginInvoke(disp_delegate, InputBuf);//disp_delegate是定義的委托事件,在委托事件中調(diào)用修改UI的程序 } catch (TimeoutException ex) //超時處理 { MessageBox.Show(ex.ToString()); } } //更新UI界面 public void DispUI(byte[] InputBuf) { string str = System.Text.Encoding.Default.GetString(InputBuf); // Console.WriteLine(str); string strW = str.Substring(0, 2);//截取str的子串,從index=0開始截取長度為2的字符串 int OutStrW = int.Parse(strW); string strS = str.Substring(2, 2);//截取str的子串,從index=2開始截取長度為2的字符串 int OutStrS = int.Parse(strS); OutstrWen = (OutStrW - 4).ToString(); textBox8.Text = strW; textBox9.Text = (OutStrW - 4).ToString(); textBox10.Text = strS; textBox11.Text = (OutStrS - 10).ToString(); } |
以上這篇C# 串口接收數(shù)據(jù)中serialPort.close()死鎖的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/hexiaobao/archive/2017/11/28/7909103.html