我的事件处理程序中的交叉线程异常 [英] Cross Thread Exception in my event handler
问题描述
我在这里得到一个Cross Thread excpetion,因为我试图访问控件而不是它创建的线程。我尝试使用System.ComponentModel.BackgroundWorker类实现此目的。因为在我们的应用程序中存在一些内部问题,我不能使用它。请帮助
private System.Timers.Timer m_SystemTimer;
private form m_ProgressBox;
public MyClass()
{
InitializeComponent();
m_SystemTimer = new System。 Timers.Timer();
m_SystemTimer.Interval = 3000;
m_SystemTimer.AutoReset = false;
m_SystemTimer.Elapsed + = new System.Timers.ElapsedEventHandler(m_SystemTimer_Elapsed);
}
private void m_SystemTimer_Elapsed(object sender,System.Timers .ElapsedEventArgs e)
{
if(m_ProgressBox == null)
{
m_ProgressBox = new Form( );
m_ProgressBox.Show();
}
}
private void MyEventHandler1(对象s ender,EventArgs e)
{
m_SystemTimer.Start();
}
私有voMyEventHandler2(对象发送者,EventArgs e)
{
m_ProgressBox.Close(); //在这里抛出一个cros线程异常
}
I am getting a Cross Thread excpetion here as i am trying to access the control other than the thread it has been created. I tried achieving this using System.ComponentModel.BackgroundWorker class. Beacuse some internal issue in our app, i cannot use this. Please help
private System.Timers.Timer m_SystemTimer;
private Form m_ProgressBox;
public MyClass()
{
InitializeComponent();
m_SystemTimer = new System.Timers.Timer();
m_SystemTimer.Interval = 3000;
m_SystemTimer.AutoReset = false;
m_SystemTimer.Elapsed += new System.Timers.ElapsedEventHandler(m_SystemTimer_Elapsed);
}
private void m_SystemTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (m_ProgressBox == null)
{
m_ProgressBox = new Form();
m_ProgressBox.Show();
}
}
private void MyEventHandler1(object sender, EventArgs e)
{
m_SystemTimer.Start();
}
private voMyEventHandler2(object sender, EventArgs e)
{
m_ProgressBox.Close(); // throws a cros thread exception here
}
推荐答案
1.您无法访问该表单,因为它是在其他线程中创建的。 />
2.您应该为线程之间的相互通信设计一个新的解决方案,例如使用类成员名称closeProgress
将从voMyEventHandler2
设置为true
,并将在m_SystemTimer_Elapsed $中进行检查c $ c>和if
true
并显示表单以关闭表单并将变量置为false。
1.You cannot access that form because was created in other thread.
2.You should design a new solution for intercommunicate between thread, for example to use a class member namecloseProgress
that will be set ontrue
from yourvoMyEventHandler2
and will be checked in yourm_SystemTimer_Elapsed
and if istrue
and the form is shown to close the form and put the variable on false.
不向我们展示添加处理程序或发出事件信号的代码我只能假设您从不同的线程中提升事件 - 在这种情况下,如果不调用它们就无法访问UI控件。
Since you don't show us the code where you add the handlers or signal the events I can only assume that you are raising your events from a different thread - in which case you cannot access UI controls without Invoking them.
if (InvokeRequired)
{
Invoke(new MethodInvoker(delegate { m_ProgressBox.Close(); }));
}
else
{
m_ProgressBox.Close();
}
这篇关于我的事件处理程序中的交叉线程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!