Export (0) Print
Expand All

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)

[SerializableAttribute] 
public sealed class ExecutionContext : ISerializable
/** @attribute SerializableAttribute() */ 
public final class ExecutionContext implements ISerializable
SerializableAttribute 
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()
        {
            try
            {
                Console.WriteLine("Executing Main in the primary thread.");
                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.
                AsyncFlowControl aFC = ExecutionContext.SuppressFlow();
                Thread t1 = new Thread(new ThreadStart(DemandPermission));
                t1.Start();
                t1.Join();
                Console.WriteLine("Is the flow suppressed? " +
                    ExecutionContext.IsFlowSuppressed());
                Console.WriteLine("Restore the flow.");
                aFC.Undo();
                Console.WriteLine("Is the flow suppressed? " +
                    ExecutionContext.IsFlowSuppressed());
                Thread t2 = new Thread(new ThreadStart(DemandPermission));
                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.Start();
                t3.Join();

                // Set the context that contains the Deny.
                // Show the deny is again active.
                Thread t4 = new Thread(new ThreadStart(DemandPermission));
                t4.Start();
                t4.Join();
                // 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("In the thread executing a Demand for " +
                    "FileDialogPermission.");
                new FileDialogPermission(
                    FileDialogPermissionAccess.OpenSave).Demand();
                Console.WriteLine("Successfully demanded " +
                    "FileDialogPermission.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        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("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(
                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);
        }
    }


    // 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;
        }
    }

}

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 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

ADD
Show:
© 2014 Microsoft