之前的多线程Demo都是在输出到控制台的情况下进行的,那么,如果我们将程序运行结果输出到控件会发生什么事情呢?下面一起来看代码吧。
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 线程访问控件
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Test()
{
for (int i = 0; i < 10000; i++)
{
//线程访问控件
textBox1.Text = i.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
//创建一个线程去执行这个方法
Thread th = new Thread(Test);
//将线程设置为后台线程
th.IsBackground = true;
//标记这个线程准备就绪了,可以随时被执行,具体什么时候执行这个线程,由CPU决定
th.Start();
}
}
}
运行结果抛出了“线程间操作无效: 从不是创建控件“textBox1”的线程访问它。”的异常。
这是因为在.NET中默认是不允许跨线程访问的,我们新开了一个线程来访问主线程的控件,所以抛出了异常。那么怎么办?
可以在窗体加载的时候就将跨线程访问的检查机制给关掉,这样我们就可以跨线程访问控件了。
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 线程访问控件
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//取消跨线程的访问检查
Control.CheckForIllegalCrossThreadCalls = false;
}
public void Test()
{
for (int i = 0; i < 10000; i++)
{
//线程访问控件
textBox1.Text = i.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
//创建一个线程去执行这个方法
Thread th = new Thread(Test);
//将线程设置为后台线程
th.IsBackground = true;
//标记这个线程准备就绪了,可以随时被执行,具体什么时候执行这个线程,由CPU决定
th.Start();
}
}
}
此时,再运行我们的程序,就发现问题已经解决了,程序可以正常访问控件了。