您的位置:首页 > 编程语言 > C#

C# 子线程操作主窗体控件的解决方法

2009-07-31 10:27 453 查看
初试C#,结果发现子线程调用主窗体空间,在C#中会抛出异常,子线程和运行窗体的线程在不同的空间,这样的跨线程调用C#编译器视为危险调用方法,所以抛出异常。

使用委托和Invoke方法。

private delegate void addStatusUnSafe(string status);
public void addStatus(string status)
{
DateTime dt = System.DateTime.Now;
string now = "[" + dt.ToShortDateString() + " " + dt.ToShortTimeString() + "]";

if (this.listBoxStatus.InvokeRequired)
{
addStatusUnSafe aus = new addStatusUnSafe(addStatus);
this.listBoxStatus.Invoke(aus, new string[] { status });
}
else
{
this.listBoxStatus.Items.Add(now + status);
if (this.listBoxStatus.Items.Count > 0)
{
this.listBoxStatus.SelectedIndex = this.listBoxStatus.Items.Count - 1;
}
}

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