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

相关推荐
农村小镇哥5 小时前
C#中的字符串格式化
服务器·开发语言·c#
czhc11400756639 小时前
719:StartPoint;Margin;ResourceDictionar;Component.model;lds;
c#
-银雾鸢尾-11 小时前
C#中的万物之父——Object类
开发语言·c#
水晶石NSIS专栏11 小时前
Geek_Studio - 安卓终端调试工作台
android·c#·apk签名·coloros主题
-银雾鸢尾-11 小时前
C#中的继承
开发语言·c#
吴可可1231 天前
C#AutoCAD二次开发打断多段线
c#
-银雾鸢尾-1 天前
里氏替换原则
开发语言·c#·里氏替换原则
-银雾鸢尾-1 天前
C#中的索引器
开发语言·c#
en.en..1 天前
冒泡排序与选择排序完整对比解析
开发语言·数据结构·算法·c#·排序算法
geovindu1 天前
CSharp: Decorator Pattern
开发语言·后端·c#·装饰器模式·结构型模式