多線程怎么訪問Ui線程 git地址下載代碼
//下面總結(jié)來自 {https://blog.csdn.net/Fanbin168/article/details/39178427}
// Action action //action是一個(gè)沒有返回值色查,也沒有參數(shù)的委托薯演,相當(dāng)于public delegate void action(),但還它也可以有帶參數(shù)的,
// Action<string> action //action是有一個(gè)帶參數(shù)秧了,沒有返回值的委托跨扮,相當(dāng)于public delegate void action(string str);
// Func<string, int> func //func是一個(gè)帶參數(shù)而且?guī)Х祷刂档奈校饫ㄌ?hào)里的最后一個(gè)參數(shù)就是委托的返回值類型验毡,它相當(dāng)于public delegate int func(string str);
// Func<int> func; //當(dāng)這個(gè)func委托的尖括號(hào)里還有一個(gè)參數(shù)的時(shí)候衡创,其實(shí)這個(gè)參數(shù)是委托的返回值類型,它相當(dāng)于public delegate int func();
private void BtnOk_Click(object sender, EventArgs e)
{
//基礎(chǔ)知識(shí)
//action用法
Form2 a2 = new Form2((x, ri) => { label1.Text = ri; });
a2.ShowDialog();
return;
//多線程訪問其他UI
Thread td = new Thread(UpdateLabel2);
td.Start("更新Label");
}
public delegate string setlab(string a);
public setlab setlabDelP { get; set; }
private void UpdateLabel2(object str)
{
if (label1.InvokeRequired)
{
// 當(dāng)一個(gè)控件的InvokeRequired屬性值為真時(shí)晶通,說明有一個(gè)創(chuàng)建它以外的線程想訪問它
//Action<string> actionDelegate = (x) => { this.label1.Text = x.ToString(); };
// 或者
Action<string> actionDelegate = delegate (string txt) { this.label1.Text = txt; };
this.label1.Invoke(actionDelegate, str);
//第二種
setlabDelP = delegate (string txt) { return this.label1.Text = txt; };
this.label1.Invoke(setlabDelP, str + "第二種");
}
else
{
this.label1.Text = str.ToString();
}
}