Versión imprimible       Enviar     
Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Esta página es específica de
Microsoft Visual Studio 2005/.NET Framework 2.0

Hay además otras versiones disponibles para:
ExecutionContext (Clase)
Administra el contexto de ejecución del subproceso actual. Esta clase no se puede heredar.

Espacio de nombres: System.Threading
Ensamblado: mscorlib (en mscorlib.dll)

Visual Basic (Declaración)
<SerializableAttribute> _
Public NotInheritable Class ExecutionContext
    Implements ISerializable
Visual Basic (Uso)
Dim instance As ExecutionContext
C#
[SerializableAttribute] 
public sealed class ExecutionContext : ISerializable
C++
[SerializableAttribute] 
public ref class ExecutionContext sealed : ISerializable
J#
/** @attribute SerializableAttribute() */ 
public final class ExecutionContext implements ISerializable
JScript
SerializableAttribute 
public final class ExecutionContext implements ISerializable
XAML
No aplicable.

La clase ExecutionContext proporciona un contenedor único para toda la información correspondiente a un subproceso lógico de ejecución. Incluye contexto de seguridad, contexto de llamada y contexto de sincronización.

La clase ExecutionContext proporciona la funcionalidad para que el código de usuario capture y transfiera este contexto a los puntos asincrónicos definidos por el usuario. El Common Language Runtime garantiza que el ExecutionContext se transfiera de forma uniforme a todos los puntos asincrónicos definidos en tiempo de ejecución dentro del proceso administrado.

Un contexto de ejecución es el equivalente administrado de un apartamento COM. Dentro de un dominio de aplicación, es preciso transferir la totalidad del contexto de ejecución siempre que se transfiere un subproceso. Esta situación tiene lugar durante transferencias realizadas por el método Thread.Start, la mayoría de las operaciones de grupo de subprocesos y el cálculo de referencias de subprocesos de Formularios Windows Forms a través del suministro de mensajes de Windows. No se produce en operaciones de grupo de subprocesos no seguras (como el método UnsafeQueueUserWorkItem) que no transfieren la pila comprimida. Siempre que la pila comprimida fluye, también fluyen el principal administrado, la sincronización, la configuración regional y el contexto del usuario. La clase ExecutionContext proporciona los métodos Capture y CreateCopy para obtener el contexto de ejecución y el método Run para establecer el contexto de ejecución del subproceso actual.

Un ExecutionContext que está asociado con un subproceso no se puede establecer en otro subproceso. Si intenta hacerlo, se producirá una excepción. Para difundir ExecutionContext de un subproceso a otro, realice una copia del ExecutionContext.

Internamente, el ExecutionContext almacena todos los datos que está asociados con LogicalCallContext. Esto permite difundir los datos de LogicalCallContext cuando se copia ExecutionContext y se transfiere.

En el siguiente ejemplo de código se muestra el uso de miembros de la clase ExecutionContext.

Visual Basic
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.
C#
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.
 */
C++
using namespace System;
using namespace System::Threading;
using namespace System::Security;
using namespace System::Collections;
using namespace System::Security::Permissions;
using namespace System::Runtime::Serialization;
using namespace System::Runtime::Remoting::Messaging;

// One means of communicating between client and server is
// to use the CallContext class. Calling CallContext effectively puts the data
// in a thread local store. This means that the information is available
// to that thread or logical thread (across application domains) only.

[Serializable]
public ref class CallContextString: public ILogicalThreadAffinative
{
private:
   String^ _str;

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

   virtual String^ ToString() override 
   {
      return _str;
   }

};

public ref class ContextBoundType: public ContextBoundObject
{
private:
   DateTime starttime;

public:
   ContextBoundType()
   {
      Console::WriteLine( "An instance of ContextBoundType has been created." );
      starttime = DateTime::Now;
   }

   [SecurityPermissionAttribute(SecurityAction::Demand, Flags = SecurityPermissionFlag::Infrastructure)]
   DateTime GetServerTime()
   {
      Console::WriteLine( "The time requested by a client." );
      
      // This call overwrites the client's
      // CallContextString.
      CallContext::SetData( "ServerThreadData", gcnew CallContextString( "This is the server side replacement string." ) );
      return DateTime::Now;
   }

};

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

};

void ExecutionContextMethods()
{
   
   // Generate a call context for this thread.
   ContextBoundType^ cBT = gcnew ContextBoundType;
   cBT->GetServerTime();
   ExecutionContext ^ eC1 = ExecutionContext::Capture();
   
   ExecutionContext ^ eC2 = eC1->CreateCopy();
   
   Console::WriteLine( "\nThe hash code for the first execution context is: {0}", 
      eC1->GetHashCode() );
   
   // Create a SerializationInfo object to be used for getting the object data.
   SerializationInfo^ sI = gcnew SerializationInfo( ExecutionContext::typeid, gcnew FormatterConverter );
   eC1->GetObjectData( sI, StreamingContext(StreamingContextStates::All) );
   LogicalCallContext^ lCC = dynamic_cast<LogicalCallContext^>(sI->GetValue( "LogicalCallContext", LogicalCallContext::typeid ));
   
   // The logical call context object should contain the previously created call context.
   Console::WriteLine( "Is the logical call context information available? {0}", lCC->HasInfo );
   
};

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

int main()
{
   try
   {
      Thread::CurrentThread->Name = "Main";

      Console::WriteLine( "Executing Main() in the primary application thread (\"{0}\").",
         Thread::CurrentThread->Name );
      FileDialogPermission^ fdp = gcnew FileDialogPermission( FileDialogPermissionAccess::OpenSave );
      fdp->Deny();
      
      // Capture the execution context containing the Deny.
      ExecutionContext ^ eC = ExecutionContext::Capture();
      
      // Suppress the flow of the execution context across threads.
      Console::WriteLine("Suppress the flow of the execution context.");
      AsyncFlowControl aFC = ExecutionContext::SuppressFlow();
      Console::WriteLine( "Is the flow suppressed? {0}", 
         ExecutionContext::IsFlowSuppressed() );

      Thread^ t1 = gcnew Thread( gcnew ThreadStart( &DemandPermission ) );
      t1->Name = "T1";
      t1->Start();
      t1->Join();
      
      Console::WriteLine( "Restore the flow." );
      aFC.Undo();
      Console::WriteLine( "Is the flow suppressed? {0}", ExecutionContext::IsFlowSuppressed() );
      
      Thread^ t2 = gcnew Thread( gcnew 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 = gcnew Thread( gcnew 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.
      ContextCallback^ callback = gcnew ContextCallback(&CallbackInContext);
      ExecutionContext::Run(eC, callback, nullptr);

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

/* 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
Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Windows 98, Windows 2000 Service Pack 4, Windows Millennium, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter

Microsoft .NET Framework 3.0 es compatible con Windows Vista, Microsoft Windows XP SP2 y Windows Server 2003 SP1.

.NET Framework

Compatible con: 3.0, 2.0
© 2009 Microsoft Corporation. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker