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

相关推荐
:mnong35 分钟前
Superpowers 项目设计分析
java·c语言·c++·python·c#·php·skills
我是唐青枫38 分钟前
C#.NET 分布式事务 深入解析:TCC、Saga、Outbox 与落地取舍
分布式·c#·.net
CSharp精选营2 小时前
.NET 8 性能优化实战:让你的应用起飞
性能优化·c#·.net·技术干货
fie88896 小时前
C# 文件分割与合并工具设计与实现
开发语言·c#
ytttr8738 小时前
C# 读取数据库表结构工具设计与实现
开发语言·数据库·c#
鸽子一号8 小时前
c#笔记之lambda表达式和linq
笔记·c#·linq
qq_391105349 小时前
TDengine C# 连接示例和授权管理
大数据·数据库·c#·时序数据库·tdengine
a177988771210 小时前
小程序码的生成与获取码中的scene
小程序·c#
无风听海10 小时前
.NET10之C# Target-typed new expression深入解析
windows·c#·.net
这辈子谁会真的心疼你11 小时前
怎么修改pdf文档属性?介绍三个方法
数据库·pdf·c#