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

相关推荐
leo__5206 小时前
C#与三菱PLC串口通信源码实现(基于MC协议)
开发语言·c#
墨瑾轩7 小时前
C# PictureBox:5个技巧,从“普通控件“到“图像大师“的蜕变!
开发语言·c#·swift
墨瑾轩7 小时前
WinForm PictureBox控件:3个让图片“活“起来的骚操作,90%的开发者都踩过坑!
开发语言·c#
Jackson@ML12 小时前
2026最新版Visual Studio安装使用指南
ide·c#·visual studio
莫生灬灬14 小时前
VueMultiBrowser 5.0 开源 - 基于 Vue3 + CEF 的多浏览器管理器
chrome·开源·c#·自动化·多开·cef3
xb113215 小时前
C#异步编程入门概念及核心概念
开发语言·c#
gc_229917 小时前
学习C#调用OpenXml操作word文档的基本用法(19:学习文档页脚类)
c#·word·openxml·页脚·footerpart
baivfhpwxf202318 小时前
C# Task.Run 和 Task.Factory.StartNew 的区别
开发语言·c#
数据的世界0119 小时前
C# 封装、继承、多态 通俗解释
c#
人工智能AI技术20 小时前
【C#程序员入门AI】AI应用的操作系统:Semantic Kernel 2026实战
人工智能·c#