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

相关推荐
“抚琴”的人4 小时前
C# 取消机制(CancellationTokenSource/CancellationToken)
开发语言·c#·wpf·1024程序员节·取消机制
helloworddm6 小时前
Orleans Grain Directory 系统综合分析文档
c#·1024程序员节
dengzhenyue8 小时前
C# 初级编程
开发语言·c#
津津有味道16 小时前
ISO18000-6C协议UHF6C超高频RFID读写C#源码
c#·uhf6c·超高频·iso18000-6c
白雪公主的后妈16 小时前
Auto CAD二次开发——创建圆弧对象
c#·cad二次开发·创建圆弧对象
weixin_3077791319 小时前
C#程序实现将MySQL的存储过程转换为Azure Synapse Dedicated SQL Pool的T-SQL存储过程
c#·自动化·云计算·运维开发·azure
"菠萝"21 小时前
C#知识学习-018(方法参数传递)
学习·c#·1024程序员节
CiLerLinux21 小时前
第三章 FreeRTOS 任务相关 API 函数
开发语言·单片机·物联网·c#
.NET修仙日记21 小时前
C#/.NET 微服务架构:从入门到精通的完整学习路线
微服务·c#·.net·.net core·分布式架构·技术进阶
歪歪1001 天前
在C#中详细介绍一下Visual Studio中如何使用数据可视化工具
开发语言·前端·c#·visual studio code·visual studio·1024程序员节