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

相关推荐
淡海水7 小时前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
asdzx678 小时前
如何使用 C# 提取 PPT 文本与图片
c#·ppt·提取文本
2501_9307077815 小时前
使用C#代码使用条件格式为 Excel 隔行设置颜色
c#·excel
何以解忧唯有撸码18 小时前
【开源】c#造个轮子-日程安排工具
c#·自定义控件
周杰伦fans19 小时前
CAD菜单栏和工具栏都不见了,怎么显示?
其他·c#
曹牧19 小时前
C#:HashSet<T> 去重
c#
czhc114007566319 小时前
起点、口径与因果:今天用错的七把尺子
c#
c#上位机1 天前
C#上位机项目实战——Task.Run执行带参数的方法
c#·上位机
Lost of 程序猿2 天前
用 YARP 为 .NET 微服务搭一座“立交桥“:路由转发与生产配置实践
c#·asp.net
点纭2 天前
C 语言 第七章 常用函数(3)
c语言·开发语言·算法·oracle·c#