线程和UI交互的普遍用法
using
System;
using
System.Windows.Forms;
using
System.Threading;
namespace
ThreadBeginInvokeAPP
{
publicpartialclassmainFrm : Form
{
public mainFrm()
{
InitializeComponent();
Thread t = newThread(newThreadStart(ChangeLabel));
t.Start();
//运行线程
}
privatedelegatevoidSetLabelTextDelegate(int number); //委托
privatevoid mainFrm_Load(object sender, EventArgs e)
{
}
privatevoid ChangeLabel() //待执行方法
{
for (int i = 0; i < 100; ++i)
{
SetLabelText(i);
Thread.Sleep(1000);
}
}
privatevoid SetLabelText(int number)
{
if (this.InvokeRequired) //如果需要进行ui和线程的交互
{
this.BeginInvoke(newSetLabelTextDelegate(SetLabelText), newobject[] { number }); //进行委托代理
}
else//如果不必进行ui和线程的交互
{
this.lblNum.Text = number.ToString(); //直接运行
}
}
privatevoid mainFrm_FormClosing(object sender, FormClosingEventArgs e)
{
Environment.Exit(0); //退出线程
}
}
}