Pieter
Pieter

Reputation: 32805

InvalidAsynchronousStateException in function that checks if invoke is required for control

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:

InvalidAsynchronousStateException

What does this mean and how do I prevent it?

Upvotes: 3

Views: 1806

Answers (1)

JaredPar
JaredPar

Reputation: 755367

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.

Upvotes: 2

Related Questions