实现跨线程访问UI控件的3种方法

时间:2022-04-12 18:34:34
namespace 多线程
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
} private void Form2_Load(object sender, EventArgs e)
{
//1.New 一个thread.
//给新创建的thread绑一个带参的方法ParameterizedThreadStart
new Thread((ParameterizedThreadStart)(Dosomething)).Start();
//如果绑的是无参的方法,就用ThreadStart
//new Thread((ThreadStart)(Dosomething)).Start(); //2.在线程池里面做.
ThreadPool.QueueUserWorkItem(new WaitCallback(Dosomething)); //3.用backgroundworker
using (BackgroundWorker bw = new BackgroundWorker())
{
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerAsync();
}
} private void bw_DoWork(object sender, DoWorkEventArgs e)
{
Dosomething("");
} private void Dosomething(object o)
{
var text = "跨线程设值";
UpdateTextboxText(text);
} private void UpdateTextboxText(string text)
{
if (this.InvokeRequired)
{
//this.Invoke((EventHandler)(SetText),new object[] {text});
//this.Invoke((MethodInvoker)(delegate { textBox1.Text = text; }));
this.Invoke((Action)( delegate {UpdateTextboxText(text);}));
//其中Action,MethodInvoker,Func<>,EventHandler都是系统定义好的委托类型
}
else
{
textBox1.Text = text;
}
}
}
}