跨线程访问控件一

跨线程访问控件

namespace WindowsFormsApplication4

{

public
partial
class
Form1 : Form

{

public Form1()

{

InitializeComponent();

}

 
 

private
void button1_Click(object sender, EventArgs e)

{

Thread thd = new
Thread(thd1);

thd.Start();

}

 
 

private
void thd1()

{

Invoke(new
Action(() => { this.label1.Text = DateTime.Now.ToLongTimeString(); }));

 
 

}

}

}

 
 

异步

namespace WindowsFormsApplication3

{

public
partial
class
Form1 : Form

{

public Form1()

{

InitializeComponent();

}

 
 

private
void button1_Click(object sender, EventArgs e)

{

 
 

printdatetime();

 
 

}

 
 

private
async
void printdatetime()

{

this.button1.Enabled = false;

await pt();

this.button1.Enabled = true;

}

private
Task pt()

{

Task tk = Task.Run(

() =>

{

for(int i=0;i<100;i++)

{

Thread.Sleep(1000);

this.label1.Text=DateTime.Now.ToString();

}

}

);

return tk;

}

}

}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注