串口通信:在使用TextBox空間顯示數據時,因為要顯示大量的接收到的數據,當數據量大且快速(串口1ms發送一條數據)時,使用+=的方式仍然會造成界面的卡頓(已使用多線程處理),但使用AppendText效果就會好一點。
代碼:
1 Thread dataThread = new Thread(delegate() 2 { 3 while (threadFlag) 4 { 5 if (Port != null && Port.IsOpen) 6 { 7 length = Port.BytesToRead; 8 if (length > 0) 9 { 10 11 bytes = new byte[length]; 12 Port.Read(bytes, 0, length); 13 14 tcp.SendData(bytes); 15 16 if (textBox.InvokeRequired) 17 { 18 19 textBox.Invoke(new Action<string>(s => 20 { 21 textBox.AppendText(s + Environment.NewLine); 22 textBox.SelectionStart = textBox.TextLength; 23 textBox.ScrollToCaret(); 24 25 }), System.Text.Encoding.ASCII.GetString(bytes)); 26 27 } 28 else 29 { 30 textBox.AppendText(System.Text.Encoding.ASCII.GetString(bytes) + Environment.NewLine); 31 textBox.SelectionStart = textBox.TextLength; 32 textBox.ScrollToCaret(); 33 34 } 35 } 36 37 } 38 Thread.Sleep(1); 39 } 40 41 }); 42 dataThread.IsBackground = true; 43 dataThread.Name = PortName; 44 dataThread.Start(); 45 } 46 47 }