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、运行结果

相关推荐
浅陌sss9 小时前
Xlua中C#引用Lua变量,导致Lua侧的GC无法回收的原因及解决方法
c#·lua
棉晗榜9 小时前
c#模拟鼠标点击左键
c#
爱吃香蕉的阿豪11 小时前
在c#中虚方法和抽象类的区别
深度学习·c#·.netcore
晚秋大魔王13 小时前
C# 添加图标
c#·visual studio code
shepherd枸杞泡茶13 小时前
第3章 .NETCore核心基础组件:3.1 .NET Core依赖注入
开发语言·c#·.net·.netcore
yuanpan14 小时前
C#的async异步方法里如果使用了await,那么它跟同步方法有什么区别?
开发语言·c#
CodeCraft Studio16 小时前
.NET版PDF处理控件Aspose.PDF教程:在 C# 中将 TIFF 文件转换为 PDF
pdf·c#·.net
斯内科17 小时前
C#使用文件读写操作实现仙剑五前传称号存档修改
c#·二进制·修改器
虫洞没有虫1 天前
《Python与C#:虚拟机与元宇宙的次元战争》
开发语言·c#
yuanpan1 天前
C#中的动态类型用法总结带演示代码
windows·microsoft·c#