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

相关推荐
Chen—LSN11 小时前
C语言——文件操作(2)
c语言·开发语言·c++·经验分享·笔记·算法·c#
淡海水14 小时前
00-Unity和C#的GC剖析与对比-全篇导览
unity·c#·游戏引擎·gc
fogota14 小时前
C# `string.Join` 处理 `List<int>`
windows·c#
Behavior17 小时前
Unity 手游动态更换 App 图标 — Android 与 iOS 双端技术方案
c#·unity3d·游戏开发
周杰伦fans17 小时前
构建真正智能的CAD AI绘图代理
开发语言·人工智能·c#
UIU11421 小时前
递归算法与汉诺塔
c++·学习·算法·c#·递归
CSharp精选营1 天前
我用 ASP.NET Core 做了个水稻病虫害检查系统
c#·毕业设计·.net core·码农刚子
唐青枫1 天前
我用 C# 开发了一款电子发票自动整理工具
c#·.net
下页、再停留1 天前
【C#桌面客户端系列学习-2】在原来窗口基础上打开新窗口
c#·visual studio
Behavior1 天前
Unity 手游 iOS Deep Link 唤醒全流程:从 URL Scheme / Universal Links 到 C# 层参数投递
c#·unity3d·游戏开发