【发布时间】:2012-02-29 18:00:42
【问题描述】:
我正在编写一个通过 GPIB 命令与多个设备通信的应用程序,并在某些设备上运行测试。我设置了一个类TestProcedure,它将启动一个新线程并运行测试。在整个测试过程中,我设置了几个自定义事件以将信息发送回 GUI。下面是一个简单事件的例子:
public event InformationEventHandler<string> TestInfoEvent;
/// <summary>
/// Event raised when information should be passed back to the main testing form.
/// </summary>
/// <param name="s">Information to send back to form.</param>
private void OnInfo(string s)
{
if (TestInfoEvent != null)
TestInfoEvent(this, s);
}
这将通过 GUI 处理,更新如下文本框:
TheTestProcedure.TestInfoEvent += new TestProcedure.InformationEventHandler<string>
(InfoOccurred);
....
private void InfoOccurred(Object sender, string s)
{
this.textBox1.Text = s + Environment.NewLine + this.textBox1.Text;
if (this.textBox1.Text.Length > 10000)
this.textBox1.Text = this.textBox1.Text.Remove(1000);
}
此事件处理似乎工作正常。我没有收到任何跨线程问题,总体上它按预期工作。但是,在另一个表单上,我刚刚添加了一个类似的事件处理程序,它会引发跨线程异常。该事件触发,发送一个简单的类,其中包含我在 InputTextBox(自定义 ComponentOne 控件)中显示的一些信息。特定控件没有 .Invoke 方法,因此我正在寻找异步访问它的替代解决方案。
所以我的问题是,事件处理程序可以安全地访问表单上的控件吗?如果不是,事件处理程序如何触发,有人可以帮助教育我,或提供一些链接信息,关于事件处理程序如何与表单控件通信?我需要锁定事件吗?
【问题讨论】:
标签: c# .net .net-3.5 event-handling