InvalidOperationException: The Undo operation encountered a context that is different from what was

Posted by McN on Stack Overflow See other posts from Stack Overflow or by McN
Published on 2010-05-14T15:17:22Z Indexed on 2010/06/05 6:32 UTC
Read the original article Hit count: 243

I got the following exception:

Exception Type: System.InvalidOperationException
Exception Message: 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).
Exception Stack: 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.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
Exception Source: mscorlib
Exception TargetSite.Name: Undo
Exception HelpLink:

The application is a Visual Studio 2005 (.Net 2.0) console application. It is a server for multiple TCP/IP connections, doing asynchronous socket reads and synchronous socket writes.

In searching for an answer I came across this post which talks about a call to Application.Doevents() which I don't use in my code.

I also found this post which has a resolution involved with Component which I also don't use in my code. The application does reference a library that I created that contains custom user controls and components, but they are not being used by the application.

Question: What caused this to happen and how do I prevent this from happening again? Or a more realistic question: What does this exception actually mean? How is "context" defined in this situation?

Anything that can help me understand what is going on would be very much appreciated.

© Stack Overflow or respective owner

Related posts about c#

Related posts about sockets