Winform跨线程访问报错问题解决
`
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Winform跨线程访问报错问题解决
{
public partial class Form1 : Form
{
private ThreadMethodHelper threadMethodHelper;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//解决方法1:取消跨线程调用(由于早期winform设计是线程不安全的,现在是线程安全的,用该方法会使winform变为线程不安全的,所以不推荐)
//CheckForIllegalCrossThreadCalls = false;
threadMethodHelper = new ThreadMethodHelper(this);
}
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(Test));
thread.Start();
}
/// <summary>
/// 在线程中直接给Form的UI控件赋值报异常:
/// System.InvalidOperationException:“线程间操作无效: 从不是创建控件“textBox1”的线程访问它。”
/// </summary>
//public void Test()
//{
// textBox1.Text = "test1";
//}
//解决方法2:
//public void Test()
//{
// this.Invoke(new Action(() =>
// {
// textBox1.Text = "test1";
// }));
// this.Invoke(new EventHandler(delegate
// {
// textBox1.Text = "test1";
// }));
//}
//解决方法3:封装一个帮助类
public void Test()
{
threadMethodHelper.SetText("test2", textBox1);
Thread.Sleep(1000);
threadMethodHelper.SetText(threadMethodHelper.GetText(textBox1), textBox2);
}
}
}
`