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

相关推荐
玩泥巴的2 小时前
.NET 8+ 飞书API实战:自动化群组管理与消息推送
c#·.net·二次开发·飞书
烛阴2 小时前
从`new`关键字开始:精通C#类与对象
前端·c#
yangshuquan2 小时前
使用 C# + IronOcr,轻松实现图片文字自动识别(OCR)和提取
c#·ocr·编程技巧·winforms
天天代码码天天3 小时前
TSR18测速雷达C#对接
c#·雷达测速·tsr18测速雷达
道一233 小时前
C#获取操作系统版本号方法
开发语言·c#
道一233 小时前
C# 判断文件是否存在的方法
开发语言·c#
唐青枫4 小时前
C#.NET 范围与索引(Range、Index)完全解析:语法、用法与最佳实践
c#·.net
矶鹬笛手11 小时前
(2.1) 信息技术及其发展
sql·计算机网络·c#
u***276112 小时前
C#数据库操作系列---SqlSugar完结篇
网络·数据库·c#
笑非不退13 小时前
C# c++ 实现程序开机自启动
开发语言·c++·c#