namespace _018_跨線程訪問控件方法
{
public partial class 跨線程訪問控件方法 : Form
{
public 跨線程訪問控件方法()
{
InitializeComponent();
//方法1:不推薦
//Control.CheckForIllegalCrossThreadCalls=false;
}
//方法2-控件對象.Invoke(Action<>,參數(shù))
private void bt1_Click(object sender, EventArgs e)
{
Task t1 = Task.Run(() =>
{
for (int i = 1; i < 100; i++)
{
Thread.Sleep(500);
//True則表示與當前線程不在同一個線程中
if (this.txtBox1.InvokeRequired)
{
//使用Invoke方法進行傳遞數(shù)據(jù),Action有參數(shù)string類型,st表示要傳的參數(shù),無返回值
//有返回值的要使用Func
//Invoket同步執(zhí)行,會卡UI
this.txtBox1.Invoke(new Action<string>((st) =>
{
this.txtBox1.Text = st;
}), i.ToString());//將要傳遞的參數(shù)寫到Lambda表達式后面,即將i的值傳遞給(st)
}
}
});
}
//方法3-控件對象.BeginInvoke(Action<>,參數(shù))
private void bt2_Click(object sender, EventArgs e)
{
Task.Run(() =>
{
for(int i = 1;i < 100; i++)
{
Thread.Sleep(1000);
//True則表示與當前線程不在同一個線程中
if (this.txtBox2.InvokeRequired)
{
//使用BeginInvoke方法進行傳遞數(shù)據(jù),Action有參數(shù)string類型,st表示要傳的參數(shù),無返回值
//有返回值的要使用Func
//BeginInvoket異步執(zhí)行,不會卡UI
this.txtBox2.BeginInvoke(new Action<string>((st) =>
{
this.txtBox2.Text += st+"、";
//this.txtBox3.Text += st + "、";//每個值后面+頓號
}),i.ToString());//將要傳遞的參數(shù)寫到Lambda表達式后面,即將i的值傳遞給(st)
}
}
});
}
//方法4-Invoke((MethodInvoker)delegate
//MethodInvoker 是一個無參數(shù)、無返回值的委托類型,用于表示可以被調(diào)用的方法
//在多線程編程中,特別是在 Windows 窗體應(yīng)用程序中,MethodInvoker 常用于安全地更新 UI 控件,
//它可以被用作給 Invoke 和 BeginInvoke 方法傳遞的委托。
private void bt3_Click(object sender, EventArgs e)
{
Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
//True則表示與當前線程不在同一個線程中,判斷多個控件
if (this.txtBox3.InvokeRequired|| this.txtBox3.InvokeRequired)
{
Invoke((MethodInvoker)delegate
{
this.txtBox3.Text = i.ToString();
this.txtBox4.Text = i.ToString();
});
}
}
});
}
}
}