日期:2014-05-17 浏览次数:20779 次
程序代码
/// <summary>
/// 按钮点击事件处理程序
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//创建新线程
Thread processorThread = null;
processorThread = new Thread(new ThreadStart(Done));
processorThread.IsBackground = true;
processorThread.SetApartmentState(ApartmentState.STA);
processorThread.Start();
}
/// <summary>
/// 更新textBox1值
/// </summary>
private void Done()
{
textBox1.Text = "www.mzwu.com";
}
运行程序点击按钮后出错,提示:线程间操作无效: 从不是创建控件“textBox1”的线程访问它。下边我们用Invoke解决这一问题:
复制内容到剪贴板 程序代码
/// <summary>
/// 按钮点击事件处理程序
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//创建新线程
Thread processorThread = null;
processorThread = new Thread(new ThreadStart(Done));
processorThread.IsBackground = true;
processorThread.SetApartmentState(ApartmentState.STA);
processorThread.Start();
}
delegate void WriteInvoke(string msg);
private void Write(string msg)
{
textBox1.Text = msg;
}
/// <summary>
/// 更新textBox1值
/// </summary>
private void Done()
{
this.Invoke(new WriteInvoke(Write), new object[] { "sms.wensima.cn" });
}
更新成功!