C# TextBox控件 显示大量数据

       串口通信:在使用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    }

 

posted @ 2015-05-27 12:32  随缘梦中人  阅读(6518)  评论(0编辑  收藏  举报