InvalidAsynchronousStateException在功能上是否需要控制调用,检查 [英] InvalidAsynchronousStateException in function that checks if invoke is required for control
问题描述
我用一个堆栈溢出用户的这一功能礼貌从的BackgroundWorker
更新控制。
I use this function courtesy of a Stack Overflow user to update controls from a BackgroundWorker
.
static void SynchronizedInvoke(ISynchronizeInvoke sync, Action action)
{
// If the invoke is not required, then invoke here and get out.
if (!sync.InvokeRequired)
{
// Execute action.
action();
// Get out.
return;
}
// Marshal to the required thread.
sync.Invoke(action, new object[] { });
}
本功能已经完美地工作到现在。我刚刚得到这个异常:
This function has worked perfectly until now. I just got this exception:
这是什么意思?我如何预防呢?
What does this mean and how do I prevent it?
推荐答案
的这里的问题是,到了 ISynchronizeInvoke
对象绑定的线程不再存在。如果你生成一个后台线程和后台任务完成之前UI线程退出发生这种情况的例子。线程不再存在,因此没有什么要调用的,你得到的异常。
The problem here is that the thread to which the ISynchronizeInvoke
object was bound to no longer exists. This can happen for example if you spawn a background thread and the UI thread exits before the background task completes. The thread no longer exists hence there's nothing to invoke to and you get the exception.
还有就是要防止这种情况没有什么好办法。行动最好的办法是包装在的try / catch
负责处理该异常的调用
电话。
There is no good way to prevent this. The best course of action is to wrap the Invoke
call in a try / catch
which handles this exception.
这篇关于InvalidAsynchronousStateException在功能上是否需要控制调用,检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!