System.InvalidOperationException: The Undo operation encountered a context that is different from wh

J

jesper.hvid

This is a problem when remotely showing a WinForm modally, when this
winform is hosted in a remoting object.

The problem ONLY appears on .NET framework 2.0.

The full exception is this:
System.InvalidOperationException: The Undo operation encountered a
context that is different from what was applied in the corresponding
Set operation. The possible cause is that a context was Set on the
thread and not reverted(undone).
at System.Threading.SynchronizationContextSwitcher.Undo()
at System.Threading.ExecutionContextSwitcher.Undo()
at System.Threading.ExecutionContext.runFinallyCode(Object userData,
Boolean exceptionThrown)
at
System.Runtime.CompilerServices.RuntimeHelpers.ExecuteBackoutCodeHelper(Object
backoutCode, Object userData, Boolean exceptionThrown)
at
System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode
code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Com

The exception cannot be handled by user code, and it only occurs when
remotely calling ShowDialog() on the remotely hosted form. Calling
Show() on the form remotely works fine, and I never get the error.

My setup is this:
A windows application exposes a remoting interface that allows remoting
clients to activate the form hosted in the windows application. The
client can pass in a HWND to show the form modally on any application
eg. Microsoft Word.

I realize that every remoting call is handled on an MTA thread, and
therefore when accessing the form I do standard multithreaded
boilerplate work to invoke the form's main thread.

The Winform is created on the windows application's main thread is
accessed through standard if InvokeRequired syntax:

if(InvokeRequired)
{
try
{
Invoke(new ShowFormDelegate(ShowForm), new object[] {
windowHandle });
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

else
{
WindowHandleWrapper wrapper = new WindowHandleWrapper(windowHandle);

ShowDialog(wrapper);

}

public class WindowHandleWrapper : IWin32Window
{
private IntPtr m_WindowHandle;

public WindowHandleWrapper(int windowHandle)
{
m_WindowHandle = new IntPtr(windowHandle);
}

public System.IntPtr Handle
{
get
{
return m_WindowHandle;
}
}

}

I have complete code samples in both 1.1 and 2.0 code, where the 2.0
code fails.

I can email the code sample if you wish, but it is a bit too lengthy to
post here.

Any ideas?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top