就拿我写的备份新浪博客的小程序说。。当我点备份按钮的时候,如果不用线程。。那窗体可能就会假死在那,一动不动的。给用户感觉很不爽的。。那要怎么解决呢??
你可能会觉的这个很简单。几行代码就搞定。
定义个方法
public void MyTest()
{
for (int i = 0; i < 100; i++)
{
this.textBox1.Text = i.ToString();
}
}private void button1_Click(object sender, EventArgs e)
{
Thread myThread = new Thread(MyTest);
myThread.Start();
}
很遗憾。
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
Additional information: 线程间操作无效: 从不是创建控件“textBox1”的线程访问它。问题解决:
1.定义 委托
delegate void myDelegate(int i);
myDelegate mydelegate = null;2.定义方法,显示消息
public void ShowMessage(int i)
{
this.textBox1.Text = i.ToString();
this.progressBar1.Value = i;
}3.定义方法,驱动消息
public void MyEvent()
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
this.BeginInvoke(mydelegate, new object[] {i});
}
}4: 运行
private void button1_Click(object sender, EventArgs e)
{
mydelegate = new myDelegate(ShowMessage);
Thread myThread = new Thread(MyEvent);
//IsBackground 是否后台
//这个属性很重要 .如果 Thread IsBackground 等于false
// 当线程还没有结束时,你点了关闭按钮
// 将抛出An unhandled exception
//of type 'System.InvalidOperationException'
//occurred in System.Windows.Forms.dll 异常
myThread.IsBackground = true;
myThread.Start();
}全都代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WinfromTheadTest
{
public partial class Form1 : Form
{
delegate void myDelegate(int i);
myDelegate mydelegate = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
mydelegate = new myDelegate(ShowMessage);
Thread myThread = new Thread(MyEvent);
//IsBackground 是否后台
//这个属性很重要 .如果 Thread IsBackground 等于false
// 当线程还没有结束时,你点了关闭按钮
// 将抛出An unhandled exception
//of type 'System.InvalidOperationException'
//occurred in System.Windows.Forms.dll 异常
myThread.IsBackground = true;
myThread.Start();
}
public void ShowMessage(int i)
{
this.textBox1.Text = i.ToString();
this.progressBar1.Value = i;
}
public void MyEvent()
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
this.BeginInvoke(mydelegate, new object[] {i});
}
}
private void button2_Click(object sender, EventArgs e)
{
//
}
}
}
点击源代码下载