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

相关推荐
张人玉1 小时前
C#Https协议相关知识点
开发语言·https·c#
Byron Loong1 小时前
【C#】VS调试——带参调试
开发语言·c#
故事不长丨1 小时前
解锁C#编程秘籍:封装、继承、多态深度剖析
开发语言·数据库·c#
努力小周2 小时前
基于STM32物联网智能老年人防摔系统
stm32·单片机·嵌入式硬件·物联网·c#·课程设计
FuckPatience2 小时前
C# 补码
开发语言·算法·c#
烽火聊员3 小时前
SSLSocket 服务器端WPF C#测试代码
开发语言·c#·wpf·ssl
wangnaisheng3 小时前
【C#】RESTful的使用
c#
缺点内向3 小时前
如何在 C# 中高效的将 XML 转换为 PDF
xml·后端·pdf·c#·.net
时光追逐者3 小时前
Visual Studio 2026 正式版下载与安装详细教程!
ide·c#·.net·.net core·visual studio
唐青枫4 小时前
C# 列表模式(List Patterns)深度解析:模式匹配再进化!
c#·.net