


在.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 _120_多线程{public partial class Form1 : Form{public Form1(){InitializeComponent();}Thread th;private void button1_Click(object sender, EventArgs e){//Thread.Sleep(3000);//Test();//会出现假死状态,主线程被占用,其他操作无法使用//创建一个线程去执行这个方法th = new Thread(Test);//前台线程Console.WriteLine(th);//Console.WriteLine(th.IsBackground);//将线程设置为后台线程th.IsBackground = true;//Console.WriteLine(th.IsBackground);th.Start();//标记这个线程准备就绪了,可以随时被执行。(由cpu执行)}public void Test(){for (int i = 0; i < 100000; i++){//Console.WriteLine(i);textBox1.Text = i.ToString();//System.InvalidOperationException:“线程间操作无效: 从不是创建控件“textBox1”的线程访问它。” Test方法不是主线程//System.ComponentModel.Win32Exception:“创建窗口句柄时出错。” 在关闭程序时,文本框已经没了,但是某些原因,这里并没有马上结束还要输出,所以出错}}private void Form1_Load(object sender, EventArgs e){//取消不可跨线程访问Control.CheckForIllegalCrossThreadCalls = false;}private void Form1_FormClosing(object sender, FormClosingEventArgs e){//当你点击关闭窗口的时候,判断线程是否为nullif (th != null){//th.Abort();//线程被Abort后就不能被Start了th = null;}}}}
