public
partial
class
Form1:Form
{
public
Form1()
{
InitializeComponent();
//方法1:不进行跨线程安全检查
//System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls=false;
}
private
void
button1_Click(
object
sender,EventArgse)
{
Threadth1=
new
Thread(
new
ThreadStart(CalNum));
th1.Start();
}
private
void
CalNum()
{
//button1.Enabled=false;
int
result=0;
for
(
int
i=1;i<100000000;i++)
{
result+=i;
}
SetCalResult(result);
//button1.Enabled=true;
}
//方法2:检查是否跨线程,然后将方法加入委托,调用委托
public
delegate
void
SetTextHandler(
int
result);
private
void
SetCalResult(
int
result)
{
if
(label2.InvokeRequired==
true
)
{
SetTextHandler
set
=
new
SetTextHandler(SetCalResult);
//委托的方法参数应和SetCalResult一致
label2.Invoke(
set
,
new
object
[]{result});
//此方法第二参数用于传入方法,代替形参result
}
else
{
label2.Text=result.ToString();
}
}
}
1500字范文,内容丰富有趣,写作好帮手!