C# 检测是否已释放控件
在我的应用程序中,我有一个使用线程池执行异步操作的用户控件。 线程池方法如下所示:C# 检测是否已释放控件,c#,.net,winforms,C#,.net,Winforms,在我的应用程序中,我有一个使用线程池执行异步操作的用户控件。 线程池方法如下所示: private void AsyncFunction(object state) { ... do the calculation //refresh the grid data on the UI thread this.BeginInvoke(new MethodInvoker(() =>
private void AsyncFunction(object state)
{
... do the calculation
//refresh the grid data on the UI thread
this.BeginInvoke(new MethodInvoker(() =>
{
... update the ui
}));
}
我的问题是如果用户关闭对话框。。。用户控件被释放,我得到异常:
在创建窗口句柄之前,无法对控件调用Invoke或BeginInvoke。
您知道一种检测对话框是否已被释放的方法吗?我不想在对话框关闭时设置控件的属性。
还有别的办法解决这个问题吗
谢谢
Radu可以使用属性
try
{
if(!this.IsDisposed)
{
this.BeginInvoke(new MethodInvoker(() =>
{
// update my control
}
));
}
}
catch ( InvalidOperationException )
{
// Do something meaningful if you need to.
}
您可以尝试使用类似于同步对象的方法向工作线程发出主线程即将终止的信号。然后工作线程可以结束它的执行。我不知道我怎么会错过它。我显式地搜索了它:)在调用
BeginInvoke
之前,您需要检查IsDisposed
,因为如果释放了控件,它就会失败。当其他线程在IsDisposed检查之后和BeginInvoke调用之前处理控件时,这不会产生问题吗?@讽刺的是,会的。这里最简单可靠的解决方案是在try.中使用BeginInvoke()。。catch(invalidooperationexception){}
@max:有没有不使用异常的典型解决方案?实际上它并不能解决100%的情况。见下文