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
看完楼主的帖子,我的心情竟是久久不能平息,受教了 好东西一定要看看! 求个链接 / 教程,楼主好人一生平安~ 这波分析到位,逻辑满分! 笑不活了,评论区比正文还精彩
已转发给朋友,一起快乐一下 我先占个楼,等下再慢慢看~ 理性围观,感觉大家说得都有道理 楼主辛苦啦,期待下一篇分享 被戳中笑点 / 泪点,太真实了!
页:
[1]
2