InvalidAsynchronousStateException in function that checks if invoke is required for control

家住魔仙堡 提交于 2019-12-07 12:43:36

问题


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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/4108177/invalidasynchronousstateexception-in-function-that-checks-if-invoke-is-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!