Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

ExecutionContext Class

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

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

[SerializableAttribute]
public sealed class ExecutionContext : ISerializable

The ExecutionContext class provides a single container for all information relevant to a logical thread of execution. This includes security context, call context, and synchronization 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()
        {
            try
            {
                Thread.CurrentThread.Name = "Main";

                Console.WriteLine("Executing Main() in the primary application thread (\"{0}\").",
                    Thread.CurrentThread.Name);
                FileDialogPermission fdp = new FileDialogPermission(
                    FileDialogPermissionAccess.OpenSave);
                fdp.Deny();
                // Capture the execution context containing the Deny.
                ExecutionContext eC = ExecutionContext.Capture();

                // Suppress the flow of the execution context.
                Console.WriteLine("Suppress the flow of the execution context.");
                AsyncFlowControl aFC = ExecutionContext.SuppressFlow();
                Console.WriteLine("Is the flow suppressed? " +
                    ExecutionContext.IsFlowSuppressed());

                Thread t1 = new Thread(new ThreadStart(DemandPermission));
                t1.Name = "T1";
                t1.Start();
                t1.Join();

                Console.WriteLine("Restore the flow.");
                aFC.Undo();
                Console.WriteLine("Is the flow suppressed? " +
                    ExecutionContext.IsFlowSuppressed());

                Thread t2 = new Thread(new ThreadStart(DemandPermission));
                t2.Name = "T2";
                t2.Start();
                t2.Join();
                // Remove the Deny.
                CodeAccessPermission.RevertDeny();
                // 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));
                t3.Name = "T3";
                t3.Start();
                t3.Join();

                // Use the Run method to execute DemandPermission in 
                // the captured context, where Deny is active. The 
                // demand fails.
                ExecutionContext.Run(eC, CallbackInContext, null);

                Console.WriteLine();
                // Demonstrate the execution context methods.
                ExecutionContextMethods();
                Console.WriteLine("Demo is complete, press Enter to exit.");
                Console.Read();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        // Execute the Demand. 
        static void DemandPermission()
        {
            try
            {
                Console.WriteLine("\nIn thread {0} executing a Demand for " +
                    "FileDialogPermission.", Thread.CurrentThread.Name);
                new FileDialogPermission(
                    FileDialogPermissionAccess.OpenSave).Demand();
                Console.WriteLine("Successfully demanded " +
                    "FileDialogPermission.");
            }
            catch (Exception e)
            {
                Console.WriteLine("Demand for FileDialogPermission failed with {0}.", e.GetType());
            }
        }

        static void ExecutionContextMethods()
        {
            // Generate a call context for this thread.
            ContextBoundType cBT = new ContextBoundType();
            cBT.GetServerTime();
            ExecutionContext eC1 = ExecutionContext.Capture();
            ExecutionContext eC2 = eC1.CreateCopy();
            Console.WriteLine("\nThe 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(
                typeof(ExecutionContext),
                new FormatterConverter());

            eC1.GetObjectData(
                sI,
                new StreamingContext(StreamingContextStates.All));

            LogicalCallContext lCC = (LogicalCallContext)sI.GetValue(
                "LogicalCallContext",
                typeof(LogicalCallContext));

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

        static void CallbackInContext(object state)
        {
            // The state is not used in this example.
            DemandPermission();
        }
    }


    // 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.
    [Serializable]
    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 " +
                "created.");
            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.
            CallContext.SetData(
                "ServerThreadData",
                new CallContextString("This is the server side replacement " +
                "string."));
            return DateTime.Now;
        }
    }

}

/* This code produces output similar to the following:

Executing Main() in the primary application thread ("Main").
Suppress the flow of the execution context.
Is the flow suppressed? True

In thread T1 executing a Demand for FileDialogPermission.
Successfully demanded FileDialogPermission.
Restore the flow.
Is the flow suppressed? False

In thread T2 executing a Demand for FileDialogPermission.
Demand for FileDialogPermission failed with System.Security.SecurityException.

In thread T3 executing a Demand for FileDialogPermission.
Successfully demanded FileDialogPermission.

In thread Main executing a Demand for FileDialogPermission.
Demand for FileDialogPermission failed with System.Security.SecurityException.

An instance of ContextBoundType has been created.
The time requested by a client.
A CallContextString has been created.

The hash code for the first execution context is: 58225482
Is the logical call context information available? True
Demo is complete, press Enter to exit.
 */

System.Object
  System.Threading.ExecutionContext

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 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0

Community Additions

Show:
© 2014 Microsoft