Windows apps
Collapse the table of content
Expand the table of content
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)

'Declaration
<SerializableAttribute> _
Public NotInheritable Class ExecutionContext
	Implements ISerializable
'Usage
Dim instance As ExecutionContext

/** @attribute SerializableAttribute() */ 
public final class ExecutionContext implements ISerializable
SerializableAttribute 
public final class ExecutionContext implements ISerializable
Not applicable.

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.

Imports System
Imports System.Threading
Imports System.Security
Imports System.Collections
Imports System.Security.Permissions
Imports System.Runtime.Serialization
Imports System.Runtime.Remoting.Messaging
Imports Microsoft.VisualBasic

Class ExecutionContextSample

    <MTAThread()> _
    Shared Sub Main()
        Try
            Thread.CurrentThread.Name = "Main"

            Console.WriteLine("Executing Main() in the primary application thread (""{0}"").", _
                Thread.CurrentThread.Name)
            Dim fdp As New FileDialogPermission(FileDialogPermissionAccess.OpenSave)
            fdp.Deny()
            ' Capture the execution context containing the Deny.
            Dim eC As ExecutionContext = ExecutionContext.Capture()

            ' Suppress the flow of the execution context.
            Console.WriteLine("Suppress the flow of the execution context.")
            Dim aFC As AsyncFlowControl = ExecutionContext.SuppressFlow()
            Console.WriteLine("Is the flow suppressed? " & ExecutionContext.IsFlowSuppressed())

            Dim t1 As New Thread(AddressOf DemandPermission)
            t1.Name = "T1"
            t1.Start()
            t1.Join()

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

            Dim t2 As New Thread(AddressOf DemandPermission)
            t2.Name = "T2"
            t2.Start()
            t2.Join()
            ' Remove the Deny.
            CodeAccessPermission.RevertDeny()
            ' Capture the context that does not contain the Deny.
            Dim eC2 As ExecutionContext = ExecutionContext.Capture()
            ' Show that the Deny is no longer present.
            Dim t3 As New Thread(AddressOf 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, AddressOf CallbackInContext, Nothing)

            Console.WriteLine()
            ' Demonstrate the execution context methods.
            ExecutionContextMethods()
            Console.WriteLine("Demo is complete, press Enter to exit.")
            Console.Read()
        Catch e As Exception
            Console.WriteLine(e.Message)
        End Try
    End Sub 'Main

    ' Execute the Demand.
    Shared Sub DemandPermission()
        Try
            Console.WriteLine(vbCrLf & _
                    "In thread {0} executing a Demand for FileDialogPermission.", _
                    Thread.CurrentThread.Name)
            Dim fDP As New FileDialogPermission(FileDialogPermissionAccess.OpenSave)
            fDP.Demand()
            Console.WriteLine("Successfully demanded FileDialogPermission.")
        Catch e As Exception
            Console.WriteLine("Demand for FileDialogPermission failed with {0}.", _
                e.GetType())
        End Try
    End Sub 'DemandPermission


    Shared Sub ExecutionContextMethods()
        ' Generate a call context for this thread.
        Dim cBT As New ContextBoundType()
        cBT.GetServerTime()
        Dim eC1 As ExecutionContext = ExecutionContext.Capture()
        Dim eC2 As ExecutionContext = eC1.CreateCopy()
        Console.WriteLine(vbCrLf & "The hash code for the first execution context is: " _
            & eC1.GetHashCode())
        ' Create a SerializationInfo object to be used for getting the object data.
        Dim sI As New SerializationInfo(GetType(ExecutionContext), New FormatterConverter())
        eC1.GetObjectData(sI, New StreamingContext(StreamingContextStates.All))
        Dim lCC As LogicalCallContext = CType(sI.GetValue("LogicalCallContext", GetType(LogicalCallContext)), LogicalCallContext)
        ' The logical call context object should contain the previously created call context.
        Console.WriteLine(("Is the logical call context information available? " & lCC.HasInfo))
    End Sub 'ExecutionContextMethods

    Shared Sub CallbackInContext(ByVal state As Object)

        ' The state is not used in this example.
        DemandPermission()

    End Sub

End Class 'ExecutionContextSample


Public Class ContextBoundType
    Inherits ContextBoundObject
    Private starttime As DateTime


    Public Sub New()
        Console.WriteLine("An instance of ContextBoundType has been created.")
        starttime = DateTime.Now
    End Sub 'New

    <SecurityPermissionAttribute(SecurityAction.Demand, Flags:=SecurityPermissionFlag.Infrastructure)> _
    Public Function GetServerTime() As DateTime
        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
    End Function 'GetServerTime
End Class 'ContextBoundType

' 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
    Implements ILogicalThreadAffinative 
    Private _str As String = ""

    Public Sub New(ByVal str As String)
        _str = str
        Console.WriteLine("A CallContextString has been created.")
    End Sub 'New

    Public Overrides Function ToString() As String
        Return _str
    End Function 'ToString
End Class 'CallContextString

' This code example 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 98, Windows Server 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 Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0

Community Additions

Show:
© 2017 Microsoft