C#基于事件异步模式的实现2(续)

1、代码

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、运行结果
在这里插入图片描述

相关推荐

  1. C#基于事件异步模式实现实例

    2024-07-12 10:32:07       23 阅读
  2. C# 基于事件观察者模式

    2024-07-12 10:32:07       46 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 10:32:07       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 10:32:07       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 10:32:07       58 阅读
  4. Python语言-面向对象

    2024-07-12 10:32:07       69 阅读

热门阅读

  1. AI正在取代程序猿?

    2024-07-12 10:32:07       24 阅读
  2. React@16.x(52)Redux@4.x(1)- 核心概念

    2024-07-12 10:32:07       22 阅读
  3. EtherCAT设备描述中的诊断消息

    2024-07-12 10:32:07       23 阅读
  4. 用虚拟机,可以在x86的电脑上虚拟出arm的电脑吗

    2024-07-12 10:32:07       21 阅读
  5. WSGI 服务器教程:`start_response` 方法解析

    2024-07-12 10:32:07       23 阅读
  6. Python面试题:如何在 Python 中解析 XML 文件?

    2024-07-12 10:32:07       21 阅读
  7. VSCode中多行文本的快速前后缩进

    2024-07-12 10:32:07       19 阅读
  8. [手机Linux PostmarketOS]三, Alpine Linux命令使用

    2024-07-12 10:32:07       23 阅读
  9. Vscode连接存在私钥的远程服务器

    2024-07-12 10:32:07       25 阅读
  10. leetcode热题100.单词拆分(动态规划进阶)

    2024-07-12 10:32:07       27 阅读
  11. ubuntu文件夹加密

    2024-07-12 10:32:07       23 阅读