internal static ExecutionContextSwitcher SetExecutionContext(ExecutionContext executionContext)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
BCLDebug.Assert(executionContext != null, "ExecutionContext cannot be null here.");
// Set up the switcher object to return;
ExecutionContextSwitcher ecsw = new ExecutionContextSwitcher();
ecsw.thread = Thread.CurrentThread;
ecsw.prevEC = Thread.CurrentThread.GetExecutionContextNoCreate(); // prev
ecsw.currEC = executionContext; //current
// Update the EC on thread
Thread.CurrentThread.SetExecutionContext(executionContext);
RuntimeHelpers.PrepareConstrainedRegions();
try
{
if (executionContext != null)
{
//set the security context
SecurityContext sc = executionContext.SecurityContext;
if (sc != null)
{
// non-null SC: needs to be set
SecurityContext prevSeC = (ecsw.prevEC != null) ? ecsw.prevEC.SecurityContext : null;
ecsw.scsw = SecurityContext.SetSecurityContext(sc, prevSeC, ref stackMark);
}
else if (!SecurityContext.CurrentlyInDefaultFTSecurityContext(ecsw.prevEC))
{
// null incoming SC, but we're currently not in FT: use static FTSC to set
SecurityContext prevSeC = (ecsw.prevEC != null) ? ecsw.prevEC.SecurityContext : null;
ecsw.scsw = SecurityContext.SetSecurityContext(SecurityContext.FullTrustSecurityContext, prevSeC, ref stackMark);
}
// set the sync context
SynchronizationContext syncContext = executionContext.SynchronizationContext;
if (syncContext != null)
{
SynchronizationContext prevSyC = (ecsw.prevEC != null) ? ecsw.prevEC.SynchronizationContext : null;
ecsw.sysw = SynchronizationContext.SetSynchronizationContext(syncContext, prevSyC);
}
// set the Host Context
HostExecutionContext hostContext = executionContext.HostExecutionContext;
if (hostContext != null)
{
ecsw.hecsw = HostExecutionContextManager.SetHostExecutionContextInternal(hostContext);
}
}
}
catch
{
ecsw.UndoNoThrow();
throw;
}
return(ecsw);
}