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

相关推荐
z落落4 小时前
C# Task WaitAll、WaitAny、WhenAll、WhenAny
开发语言·c#
玖玥拾6 小时前
C# 语言进阶(十四)Unity UI界面开发 + 网络消息联动
服务器·开发语言·网络·ui·unity·c#·游戏引擎
czhc11400756637 小时前
712:Atta. cursor;ToggleButton
c#
玖玥拾8 小时前
C# 语言进阶(十三)网络 DLL 库分层设计
服务器·开发语言·网络·网络协议·c#
雪靡9 小时前
WPF PerMonitorV2 下的跨窗口问题
c#·wpf
苍狼唤9 小时前
SQL+C# 增删改查(练习)
数据库·sql·c#
LibraJM1 天前
一种适合程序员的 Agent 协作方式的实践
c#·copilot·agents
旋律翼21 天前
Qt Bridges for C# 深度技术解析
开发语言·qt·c#
吴可可1231 天前
判断多段线方向的鞋带公式法
c#