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 小时前
C# | Serilog 新手入门
开发语言·c#·.net·log
在世修行3 小时前
从零打造 C# 工业视觉检测系统(七):串口通信 SerialPort 封装与开发
开发语言·c#·modbus rtu·rs232/rs485
NoteStream8 小时前
【C语言基础】分支和循环(上)
c语言·开发语言·c++·经验分享·笔记·算法·c#
lzhdim10 小时前
C# 通过 Windows API 实现进程内存读写操作
开发语言·windows·c#
-银雾鸢尾-10 小时前
C#中的预处理指令
开发语言·c#
dalong1010 小时前
Savitzky-Golay 的C# 实现
开发语言·kotlin·c#
猿长大人11 小时前
C# | Autofac 新手指南:从零理解依赖注入与组件装配
c#·.net·di·依赖注入
show43311 小时前
多格式导出怎么做?2026免费小程序TXT/SRT实践
开发语言·小程序·c#
czhaii12 小时前
word插入表格排版创建或编辑应用技巧
ui·c#·xhtml
在世修行13 小时前
从零打造 C# 工业视觉检测系统(十一):Task 异步编程与实时性保障
开发语言·c#·task异步