gkket 发表于 2021-9-12 16:26:53

Winform 多线程中处理UI控件, 解决线程安全引起的异常

Winform 多线程中处理UI控件, 解决线程安全引起的异常using System;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApp10
{
    public partial class Form1 : Form
    {
      public Form1()
      {
            InitializeComponent();
      }

      /*
            在窗体拖拽2个button,1个label
         */
      private void button1_Click(object sender, EventArgs e)
      {
            Thread thread = new Thread(Test1);
            thread.Start();
      }

      // 线程中直接操作控件会引发线程安全异常
      // Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.'
      private void Test1()
      {
            for (int i = 0; i < 1000; ++i)
            {
                label1.Text = i.ToString();
            }
      }

      // Control.CheckForIllegalCrossThreadCalls = false;// 可以解决掉所有控件安全异常
      private void Test2()
      {
            Control.CheckForIllegalCrossThreadCalls = false;
            for (int i = 0; i < 1000; ++i)
            {
                label1.Text = i.ToString();
            }
      }

      // 在线程中用委托操作UI控件
      delegate void InvokeHandler();
      private void Test3()
      {
            for (int i = 0; i < 1000; ++i)
            {
                // net 2.0
                this.Invoke(new InvokeHandler(delegate ()
                {
                  label1.Text = i.ToString();
                }));
            }
      }

      // 在线程中用委托操作UI控件
      private void Test4()
      {
            for (int i = 0; i < 1000; ++i)
            {
                // net 3.5 以上
                this.Invoke((Action)(() =>
                {
                  label1.Text = i.ToString();
                }));
            }
      }
    }
}

来源:C#社区
原文:https://www.hicsharp.com/a/aa141b160dfc44d0a1b9a43e0a0947af




meety0urmakers 发表于 2021-9-12 16:26:53

看完楼主的帖子,我的心情竟是久久不能平息,受教了

924685652 发表于 2021-9-12 17:38:07

好东西一定要看看!

YTX 发表于 2025-11-12 12:49:51

求个链接 / 教程,楼主好人一生平安~

陈尚志 发表于 2025-11-12 13:03:41

这波分析到位,逻辑满分!

wyq20201974 发表于 2025-11-12 14:45:31

笑不活了,评论区比正文还精彩
已转发给朋友,一起快乐一下

gk-auto 发表于 2025-11-14 23:13:20

我先占个楼,等下再慢慢看~

孙芹 发表于 2025-11-15 00:10:53

理性围观,感觉大家说得都有道理

xz270727378 发表于 2025-11-15 00:15:32

楼主辛苦啦,期待下一篇分享

wxz_100 发表于 2025-11-15 00:18:15

被戳中笑点 / 泪点,太真实了!
页: [1] 2
查看完整版本: Winform 多线程中处理UI控件, 解决线程安全引起的异常