ExecutionContext Class

Note: This class is new in the .NET Framework version 2.0.

Manages the execution context for the current thread. This class cannot be inherited.

Namespace: System.Threading
Assembly: mscorlib (in mscorlib.dll)

public sealed class ExecutionContext : ISerializable
/** @attribute SerializableAttribute() */ 
public final class ExecutionContext implements ISerializable
public final class ExecutionContext implements ISerializable

The ExecutionContext class provides a single container for all information relevant to a logical thread of execution. This includes security context, call context, synchronization context, localization context, and transaction context.

The ExecutionContext class provides the functionality for user code to capture and transfer this context across user-defined asynchronous points. The common language runtime ensures that the ExecutionContext is consistently transferred across runtime-defined asynchronous points within the managed process.

An execution context is the managed equivalent of a COM apartment. Within an application domain, the entire execution context must be transferred whenever a thread is transferred. This situation occurs during transfers made by the Thread.Start method, most thread pool operations, and Windows Forms thread marshaling through the Windows message pump. It does not occur in unsafe thread pool operations (such as the UnsafeQueueUserWorkItem method), which do not transfer the compressed stack. Wherever the compressed stack flows, the managed principal, synchronization, locale, and user context also flow. The ExecutionContext class provides the Capture and CreateCopy methods to get the execution context and the Run method to set the execution context for the current thread.

An ExecutionContext that is associated with a thread cannot be set on another thread. Attempting to do so will result in an exception being thrown. To propagate the ExecutionContext from one thread to another, make a copy of the ExecutionContext.

Internally, the ExecutionContext stores all data that is associated with the LogicalCallContext. This allows the LogicalCallContext data to be propagated when the ExecutionContext is copied and transferred.

The following code example shows the use of members of the ExecutionContext class.

using System;
using System.Threading;
using System.Security;
using System.Collections;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Runtime.Remoting.Messaging;

namespace Contoso
    class ExecutionContextSample
        static void Main()
                Console.WriteLine("Executing Main in the primary thread.");
                FileDialogPermission fdp = new FileDialogPermission(
                // Capture the execution context containing the Deny.
                ExecutionContext eC = ExecutionContext.Capture();

                // Suppress the flow of the execution context.
                AsyncFlowControl aFC = ExecutionContext.SuppressFlow();
                Thread t1 = new Thread(new ThreadStart(DemandPermission));
                Console.WriteLine("Is the flow suppressed? " +
                Console.WriteLine("Restore the flow.");
                Console.WriteLine("Is the flow suppressed? " +
                Thread t2 = new Thread(new ThreadStart(DemandPermission));
                // Remove the Deny.
                // Capture the context that does not contain the Deny.
                ExecutionContext eC2 = ExecutionContext.Capture();
                // Show that the Deny is no longer present.
                Thread t3 = new Thread(new ThreadStart(DemandPermission));

                // Set the context that contains the Deny.
                // Show the deny is again active.
                Thread t4 = new Thread(new ThreadStart(DemandPermission));
                // Demonstrate the execution context methods.
                Console.WriteLine("Demo is complete, press Enter to exit.");
            catch (Exception e)
        // Execute the Demand.
        static void DemandPermission()
                Console.WriteLine("In the thread executing a Demand for " +
                new FileDialogPermission(
                Console.WriteLine("Successfully demanded " +
            catch (Exception e)

        static void ExecutionContextMethods()
            // Generate a call context for this thread.
            ContextBoundType cBT = new ContextBoundType();
            ExecutionContext eC1 = ExecutionContext.Capture();
            ExecutionContext eC2 = eC1.CreateCopy();
            Console.WriteLine("The hash code for the first execution " +
                "context is: " + eC1.GetHashCode());

            // Create a SerializationInfo object to be used for getting the
            // object data.
            SerializationInfo sI = new SerializationInfo(
                new FormatterConverter());

                new StreamingContext(StreamingContextStates.All));

            LogicalCallContext lCC = (LogicalCallContext)sI.GetValue(

            // The logical call context object should contain the previously
            // created call context.
            Console.WriteLine("Is the logical call context information " +
                "available? " + lCC.HasInfo);

    // One means of communicating between client and server is to use the
    // CallContext class. Calling CallContext effectivel puts the data in a thread
    // local store. This means that the information is available to that thread
    // or that logical thread (across application domains) only.
    public class CallContextString : ILogicalThreadAffinative
        String _str = "";

        public CallContextString(String str)
            _str = str;
            Console.WriteLine("A CallContextString has been created.");

        public override String ToString()
            return _str;

    public class ContextBoundType : ContextBoundObject
        private DateTime starttime;

        public ContextBoundType()
            Console.WriteLine("An instance of ContextBoundType has been " +
            starttime = DateTime.Now;
        [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.Infrastructure)]
        public DateTime GetServerTime()
            Console.WriteLine("The time requested by a client.");
            // This call overwrites the client's
            // CallContextString.
                new CallContextString("This is the server side replacement " +
            return DateTime.Now;



Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0

Community Additions