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

相关推荐
阿蒙Amon7 小时前
C#每日面试题-Array和ArrayList的区别
java·开发语言·c#
i橡皮擦9 小时前
TheIsle恐龙岛读取游戏基址做插件(C#语言)
开发语言·游戏·c#·恐龙岛·theisle
用户219916797039115 小时前
C# 14 中的新增功能
c#
垂葛酒肝汤16 小时前
放置挂机游戏的离线和在线收益unity实现
游戏·unity·c#
爱说实话17 小时前
C# 20260112
开发语言·c#
无风听海18 小时前
C#中实现类的值相等时需要保留null==null为true的语义
开发语言·c#
云草桑18 小时前
海外运单核心泡货计费术语:不计泡、计全泡、比例分泡
c#·asp.net·net·计泡·海运
精神小伙就是猛18 小时前
C# Task/ThreadPool async/await对比Golang GMP
开发语言·golang·c#