标签:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Windows; 7 using System.Windows.Controls; 8 using System.Windows.Data; 9 using System.Windows.Documents; 10 using System.Windows.Input; 11 using System.Windows.Media; 12 using System.Windows.Media.Imaging; 13 using System.Windows.Navigation; 14 using System.Windows.Shapes; 15 using System.IO.Ports; 16 using System.Threading; 17 18 namespace port 19 { 20 /// <summary> 21 /// MainWindow.xaml 的交互逻辑 22 /// </summary> 23 public partial class MainWindow : Window 24 { 25 SerialPort serialPort; 26 List<double> Va = new List<double>(); //存储电荷测量电路的输出电压 27 List<double> Vz = new List<double>(); 28 List<double> Vw = new List<double>(); 29 List<double> Vc = new List<double>(); 30 31 private AutoResetEvent are = new AutoResetEvent(false); 32 33 public void InitialPort() 34 { 35 serialPort = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One); 36 serialPort.Open(); 37 } 38 39 private void transive() //向模块发送命令 40 { 41 42 //读取通道1 格式为#AAN AA表示模块的站号 N表示通道 43 serialPort.WriteLine("#01\r"); 44 Thread.Sleep(200); 45 are.Set(); 46 47 } 48 private void recieve() //接收模块八个通道发来的数据,然后提取1-4通道的数据 49 { 50 are.WaitOne(); 51 int n1 = serialPort.BytesToRead; 52 byte[] buffer1 = new byte[n1]; //n1=58 八个通道传来的数据共58字节 53 serialPort.Read(buffer1, 0, n1); 54 byte[] bufferVa = new byte[7]; 55 byte[] bufferVz = new byte[7]; 56 byte[] bufferVw = new byte[7]; 57 byte[] bufferVc = new byte[7]; 58 for (int i = 0, j = 8; i < 7; i++, j++) //提取第一通道的数据 59 { 60 bufferVa[i] = buffer1[j]; 61 } 62 for (int i = 0, j = 15; i < 7; i++, j++) //提取第二通道的数据 63 { 64 bufferVz[i] = buffer1[j]; 65 } 66 for (int i = 0, j = 22; i < 7; i++, j++) //提取第三通道的数据 67 { 68 bufferVw[i] = buffer1[j]; 69 } 70 for (int i = 0, j = 29; i < 7; i++, j++) //提取第四通道的数据 71 { 72 bufferVc[i] = buffer1[j]; 73 } 74 //线程使用到主线程中的控件 该如何解决? 75 Func<bool> func = () => 76 { 77 this.VaText.Text = Encoding.ASCII.GetString(bufferVa); 78 this.VzText.Text = Encoding.ASCII.GetString(bufferVz); 79 this.VwText.Text = Encoding.ASCII.GetString(bufferVw); 80 this.VcText.Text = Encoding.ASCII.GetString(bufferVc); 81 return true; 82 }; 83 object obj = this.Dispatcher.Invoke(func); //用于跨线程调用 84 85 } 86 87 88 public MainWindow() 89 { 90 InitializeComponent(); 91 InitialPort(); 92 } 93 94 private void StartButton_Click(object sender, RoutedEventArgs e) 95 { 96 97 for (int i = 0; i < 10; i++) 98 { 99 Thread transiveThread = new Thread(transive); 100 Thread recieveThread = new Thread(recieve); 101 transiveThread.Start(); 102 recieveThread.Start(); 103 Thread.Sleep(200); 104 } 105 106 } 107 108 } 109 }
为何每次循环之后才显示数据
标签:
原文地址:http://www.cnblogs.com/darrensun/p/4389766.html