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

相关推荐
地球驾驶员18 小时前
NX二次开发C#----C#和C++的二次开发程序如何签名?
c#
小码编匠19 小时前
C# 实现网络文件传输:打造稳定可靠的工业级工具
后端·c#·.net
MM_MS20 小时前
SQL Server数据库和Visual Studio (C#)联合编程
开发语言·数据库·sqlserver·c#·visual studio
c#上位机1 天前
halcon计算区域骨架
图像处理·人工智能·计算机视觉·c#·halcon
曹牧1 天前
C#:Dictionary类型数组
java·开发语言·c#
GeekyGuru1 天前
C#:游戏开发的高效利器
开发语言·c#
关关长语1 天前
基于NCrontab实现Covarel扩展秒级任务调度
c#·.net
足球中国1 天前
什么情况下会发生跨域
c#·dataexcel·cfucion
yue0081 天前
C# 实现电脑锁屏功能
开发语言·c#·电脑·电脑锁屏
2501_930707781 天前
如何在 C# 中分离饼图的某个区域
开发语言·c#