您的位置:首页 > 其它

在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke

2010-03-02 15:57 661 查看
/**************************************************
* 多线程下更新控件属性(测试)
* 2007-11-3 西沉
* ***********************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
delegate void SetTextCallback(string text);
delegate void EndPro();

public Form1()
{
InitializeComponent();
}

public void Set_Text(string t)
{
//第一种多线程处理方式,判断控件的InvokeRequired属性
//看是否非创建线程的调用
if (this.label1.InvokeRequired)
{
SetTextCallback bk = new SetTextCallback(this.Set_Text);
if(!this.IsDisposed)
this.Invoke(bk, new object[] { t});
}
else
{
this.label1.Text = t;
}
}
public void End_Pro()
{
this.bt1.Enabled = true;
}

public void ThreadPro()
{
for (int i = 0; i < 10; i++)
{
this.Set_Text(string.Format("记数:{0}",i));
Thread.Sleep(1000);
}

//第二种多线程处理方式,使用代理
EndPro e = new EndPro(this.End_Pro);
if (!this.IsDisposed)//注意:要判断窗体是否已销毁,否则会出现,异常提示:“在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke”
{
this.Invoke(e, new object[] { });
}
}

private void bt1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(this.ThreadPro));
t.Start();

Button bt = sender as Button;
bt.Enabled = false;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐