介绍多线程的使用,跨线程访问控件,修改控件属性
代码实现:
/// <summary>
/// 点击刷新界面显示数字-跨线程赋值文本框信息
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void buttonRefush_Click(object sender, EventArgs e)
{
this.textBoxNum.Text = "10";
Thread th = new Thread(new ThreadStart(SetValue));
th.Start();
}
/// <summary>
///循环显示数字
/// </summary>
public void SetValue()
{
for (int i = 1; i <= 10; i++)
{
if (i == 10) i = 1;
Refush(i.ToString());
Thread.Sleep(1000);
}
}
/// <summary>
/// 文本框赋值
/// </summary>
/// <param name="num">The number.</param>
private void Refush(string num)
{
if (this.InvokeRequired)
{
// BeginInvoke(new Action<string>(Refush));
Action<string> act = s => Refush(num);
// this.Invoke(new Action<string>(Refush),num);
BeginInvoke(act, num);
}
else
{
this.textBoxNum.Text = num.ToString();
}
}
/// 点击刷新界面显示数字-跨线程赋值文本框信息
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void buttonRefush_Click(object sender, EventArgs e)
{
this.textBoxNum.Text = "10";
Thread th = new Thread(new ThreadStart(SetValue));
th.Start();
}
/// <summary>
///循环显示数字
/// </summary>
public void SetValue()
{
for (int i = 1; i <= 10; i++)
{
if (i == 10) i = 1;
Refush(i.ToString());
Thread.Sleep(1000);
}
}
/// <summary>
/// 文本框赋值
/// </summary>
/// <param name="num">The number.</param>
private void Refush(string num)
{
if (this.InvokeRequired)
{
// BeginInvoke(new Action<string>(Refush));
Action<string> act = s => Refush(num);
// this.Invoke(new Action<string>(Refush),num);
BeginInvoke(act, num);
}
else
{
this.textBoxNum.Text = num.ToString();
}
}