Windows 事件与跨线程调用

需求

当我们新建一个类,通常会遇到当类的一个属性变化时,如何通知用户?比如串口收到数据,tcp 或UDP 收到网络数据时,如何及时通知用户?

1、查询是否收到,若收到,在文本框显示。

2、专门新增加一个线程,专门负责接收数据。当有数据收到时,通过"数据已收到"事件,用事件处理程序,来更新文本框。

第一种方法简单,但十分占用资源。第二种方法,涉及事件及线程安全问题。

现以第二种方法为例,进行说明。

(1) 在类中声明事件处理程序

java 复制代码
public   delegate void ReiceivedDataChgEventHandler(object sender, ReceivedDataChgEventArgs args); 
public    ReiceivedDataChgEventHandler?  ReceivedDataChg;

(2)在数据的set 方法中,加入事件处理

java 复制代码
public string ReceivedData{
  set
 	{
     string oldValue = receivedData??"";
     string newValue = value??"";
     receivedData = value;
     NewData = true;
     OnReceivedDataChg("receivedData", oldValue, newValue);
 		}
 }
 private string? receivedData;
 public virtual void OnReceivedDataChg(string name, object oldValue, object newValue)
 {
     if (ReceivedDataChg != null)
     {
         ReceivedDataChg.Invoke(this, new ReceivedDataChgEventArgs(name, oldValue, newValue));
     }
 }

3、在form中,新建类,并为ReceivedDataChg增加处理程序。特别要说明的时,由于类form并不时由serialPort类创建的,由类的实例调用form中的控件时,windows 认为类越权了。所以需要由textBox2反过来调用类的事件处理程序 "setText"。

是不是有点绕。

java 复制代码
private void button1_Click(object sender, EventArgs e)
{
    string portName = comboBox1.SelectedItem as string ?? "com1";
    sp = new(portName, 115200, 8, "1", SerialPortC.ParityBits.None);
    sp.ReceivedDataChg += SetText;
    if (sp._serialPort.IsOpen)
    {
        this.textBox1.Text = "AT";
        sp.Writeline("AT");
    }
}
public void SetText(object sender, ReceivedDataChgEventArgs args)
{
    if (this.textBox2.InvokeRequired)
    {
        this.textBox2.Invoke(SetText, this.textBox2, args);
    }
    else
    {
        this.textBox2.AppendText((string)args.NewValue);
    }
}
相关推荐
AxureMost9 小时前
C盘清理工具 LightC
windows
csdn_aspnet9 小时前
C# 高效便利的处理数据
开发语言·windows·c#
淡海水9 小时前
03-02-线性-List-T-动态数组布局-扩容与操作成本
数据结构·windows·c#·list·编译·clr·机器码
深念Y1 天前
从 Windows 迁移到 Linux 开发环境的记录
linux·windows·链接·bun·ram·imdisk
Cerman1 天前
QEMU启动OVMF shell超时分析
c语言·windows·经验分享
comedate2 天前
Windows / Linux GPU 虚拟内存布局差异与 CUDA 越界访问行为
linux·windows·mmu·cuda 越界访问
IT技术分享社区2 天前
Windows桌面时钟推荐:始终置顶、无级缩放、支持全屏游戏显示时间
windows·微软技术·电脑技巧·桌面美化·电脑干货
公子小六2 天前
基于.NET的Windows窗体编程之WinForms音频控件
windows·microsoft·c#·.net·音视频·winforms
诸神缄默不语2 天前
如何在Win11系统中找到是哪个程序占用了指定端口
windows
FL16238631292 天前
Halcon26.05下载安装教程
windows