- 打卡等级:常驻代表
- 打卡总天数:34
- 打卡月天数:6
- 打卡总奖励:9027
- 最近打卡:2025-12-17 23:15:51
管理员
- 积分
- 22569
|
Winform 多线程中处理UI控件, 多线程中不能直接操作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();
- }));
- }
- }
- }
- }
复制代码
|
|