1.跨类跨线程更新UI方法1
1.0 UI界面代码
public partial class Form1 : Form
{
private Thread myThread;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TextBox[] myTextBox = new TextBox[] { textBox1, textBox2, textBox3 };
Class1 myClass = new Class1();
#region 开启UI更新线程方法1
myThread = new Thread(new ThreadStart(delegate { myClass.UpdateUI(myTextBox); }));
myThread.Start();
#endregion 开启UI更新线程方法1
#region 开启UI更新线程方法2
//myThread = new Thread(new ParameterizedThreadStart(myClass.UpdateUI));
//myThread.Start(myTextBox);
#endregion 开启UI更新线程方法2
//对于不同类型的多个参数,可以使用object[](或其他)
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
myThread.Abort();
}
}
1.1 线程类
internal class Class1
{
public void UpdateUI(object temp)
{
TextBox[] tempTextBox = temp as TextBox[];
while (true)
{
try
{
foreach (TextBox myTextBox in tempTextBox)
{
if (myTextBox.InvokeRequired)
{
myTextBox.Invoke(new MethodInvoker(delegate { myTextBox.Text = DateTime.Now.ToLongTimeString(); }));
}
else
{
myTextBox.Text = null;
}
}
//for (int i = 0; i < text.Length; i++)
//{
// if (text[i].InvokeRequired)
// {
// text[i].Invoke(new MethodInvoker(delegate { text[i].Text = DateTime.Now.ToLongTimeString(); }));
// }
// else
// {
// text[i].Text = null;
// }
//}
}
catch
{ }
}
}
}
2.待续