Windows 事件与跨线程调用 需求当我们新建一个类通常会遇到当类的一个属性变化时如何通知用户比如串口收到数据tcp 或UDP 收到网络数据时如何及时通知用户1、查询是否收到若收到在文本框显示。2、专门新增加一个线程专门负责接收数据。当有数据收到时通过“数据已收到”事件用事件处理程序来更新文本框。第一种方法简单但十分占用资源。第二种方法涉及事件及线程安全问题。现以第二种方法为例进行说明。(1) 在类中声明事件处理程序publicdelegatevoidReiceivedDataChgEventHandler(object sender,ReceivedDataChgEventArgsargs);publicReiceivedDataChgEventHandler?ReceivedDataChg;2在数据的set 方法中加入事件处理publicstringReceivedData{set{string oldValuereceivedData??;string newValuevalue??;receivedDatavalue;NewDatatrue;OnReceivedDataChg(receivedData,oldValue,newValue);}}privatestring?receivedData;publicvirtualvoidOnReceivedDataChg(string name,object oldValue,object newValue){if(ReceivedDataChg!null){ReceivedDataChg.Invoke(this,newReceivedDataChgEventArgs(name,oldValue,newValue));}}3、在form中新建类并为ReceivedDataChg增加处理程序。特别要说明的时由于类form并不时由serialPort类创建的由类的实例调用form中的控件时windows 认为类越权了。所以需要由textBox2反过来调用类的事件处理程序 “setText。是不是有点绕。privatevoidbutton1_Click(object sender,EventArgse){string portNamecomboBox1.SelectedItemas string??com1;spnew(portName,115200,8,1,SerialPortC.ParityBits.None);sp.ReceivedDataChgSetText;if(sp._serialPort.IsOpen){this.textBox1.TextAT;sp.Writeline(AT);}}publicvoidSetText(object sender,ReceivedDataChgEventArgsargs){if(this.textBox2.InvokeRequired){this.textBox2.Invoke(SetText,this.textBox2,args);}else{this.textBox2.AppendText((string)args.NewValue);}}