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

相关推荐
开开心心_Every7 小时前
全能视频处理工具介绍说明
开发语言·人工智能·django·pdf·flask·c#·音视频
86Eric7 小时前
C# 入门学习教程(二)
c#·操作符·语句
simonkimi8 小时前
解决无法在Cursor中使用C# Dev Kit的问题
c#·cursor
枯萎穿心攻击14 小时前
ECS由浅入深第三节:进阶?System 的行为与复杂交互模式
开发语言·unity·c#·游戏引擎
小码编匠15 小时前
WPF 自定义TextBox带水印控件,可设置圆角
后端·c#·.net
水果里面有苹果15 小时前
17-C#的socket通信TCP-1
开发语言·tcp/ip·c#
阿蒙Amon1 天前
C# Linq to SQL:数据库编程的解决方案
数据库·c#·linq
iCxhust1 天前
c# U盘映像生成工具
开发语言·单片机·c#
emplace_back1 天前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#