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

相关推荐
黑咩狗夜.cm16 小时前
(aspose.words .net)内容分别固定在一行左右俩端
c#·word·.net
刚子编程16 小时前
C# Join 实战:左连接写法、字符串拼接与 EF Core 性能调优
开发语言·c#·solr·join
小清兔17 小时前
Addressable的设置打包流程
笔记·游戏·unity·c#
rockey62718 小时前
AScript中一个很有意思的语法
c#·.net·script·eval·expression·动态脚本
刚子编程18 小时前
C# Join 深度解析:参数顺序、多表关联与空值处理最佳实践
开发语言·c#·最佳实践·join·多表关联·空值处理
天天代码码天天18 小时前
C# OnnxRuntime 实现车牌检测识别
c#·车牌识别·号牌识别
刚子编程18 小时前
C# Join 进阶:GroupJoin、性能对决与自定义比较器
java·servlet·c#·join
海盗123420 小时前
C#中的IEqualityComparer<T>使用
开发语言·c#
IT策士1 天前
Python Word操作:从入门到精通
python·c#·word