System.Threading.ExecutionContextSwitcher.Undo C# (CSharp) Method

Undo() private method

private Undo ( ) : void
return void
        public void Undo()
        {
            if (thread == null)
            {
                return; // Don't do anything
            }  
            if (thread != Thread.CurrentThread)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseSwitcherOtherThread"));
            }        
            if ( currEC != Thread.CurrentThread.GetExecutionContextNoCreate())
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SwitcherCtxMismatch"));
            }
            BCLDebug.Assert(currEC != null, " ExecutionContext can't be null");


            // Any critical failure inside scsw will cause FailFast
            scsw.Undo();

            try 
            {
                HostExecutionContextSwitcher.Undo(hecsw);
            }
            finally
            {
                // Even if HostExecutionContextSwitcher.Undo(hecsw) throws, we need to revert
                // synchronizationContext. If that throws, we'll be throwing an ex during an exception
                // unwind. That's OK - we'll just have nested exceptions.
                sysw.Undo();
            }

            // restore the saved Execution Context
            Thread.CurrentThread.SetExecutionContext(prevEC);
            thread = null; // this will prevent the switcher object being used again


        }
    }

Usage Example

        public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
        {
            if (executionContext == null)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext"));
            }

            Thread currentThread          = Thread.CurrentThread;
            ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher);

            try
            {
                EstablishCopyOnWriteScope(currentThread, ref ecsw);
                ExecutionContext.Restore(currentThread, executionContext);
                callback(state);
            }
            catch
            {
                // Note: we have a "catch" rather than a "finally" because we want
                // to stop the first pass of EH here.  That way we can restore the previous
                // context before any of our callers' EH filters run.  That means we need to
                // end the scope separately in the non-exceptional case below.
                ecsw.Undo(currentThread);
                throw;
            }
            ecsw.Undo(currentThread);
        }
All Usage Examples Of System.Threading.ExecutionContextSwitcher::Undo