C#基于事件异步模式的实现2(续)

1、代码

csharp 复制代码
private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add($"The thread id is {Thread.CurrentThread.ManagedThreadId}");

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler((s1, s2) =>
            {
                Thread.Sleep(2000);
                ListBoxAcrossDomain(listBox1,$"The asynchronous thread id is {Thread.CurrentThread.ManagedThreadId}");
            });
            listBox1.Items.Add($"The test is start");
            //注册事件来实现异步
            worker.RunWorkerAsync(this);
            listBox1.Items.Add($"The test is end");
        }

        public static void ListBoxAcrossDomain(ListBox listBox,string text)
        {
            if(listBox == null) return;
            if(listBox.InvokeRequired)
            {
                listBox.Invoke(new Action(() => { listBox.Items.Add(text); }));
            }
            else
            {
                listBox.Items.Add(text);
            }
        }

2、运行结果

相关推荐
LF男男43 分钟前
MK - Grand Mahjong Game-
unity·c#
代数狂人1 小时前
《深入浅出Godot 4与C# 3D游戏开发》第一章:了解Godot与搭建开发环境
c#·游戏引擎·godot
齐鲁大虾15 小时前
新人编程语言选择指南
javascript·c++·python·c#
加号315 小时前
【C#】 WebAPI 接口设计与实现指南
开发语言·c#
unicrom_深圳市由你创科技16 小时前
上位机开发常用的语言 / 框架有哪些?
c++·python·c#
xiaoshuaishuai818 小时前
C# ZLibrary数字资源分发
开发语言·windows·c#
Eiceblue20 小时前
C# 实现 XLS 与 XLSX 格式双向互转(无需依赖 Office)
开发语言·c#·visual studio
aini_lovee21 小时前
基于C#的三菱PLC串口通信实现方案
服务器·网络·c#
光泽雨21 小时前
c#MVVM中的消息通知机制
服务器·c#
江沉晚呤时21 小时前
C# 整型溢出处理机制:checked 与 unchecked 上下文解析
c#·.net