ExecutionContext クラスとは? わかりやすく解説

ExecutionContext クラス

メモ : このクラスは、.NET Framework version 2.0新しく追加されたものです。

現在のスレッド実行コンテキスト管理します。このクラス継承できません。

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

<SerializableAttribute> _
Public NotInheritable Class
 ExecutionContext
    Implements ISerializable
Dim instance As ExecutionContext
[SerializableAttribute] 
public sealed class ExecutionContext : ISerializable
[SerializableAttribute] 
public ref class ExecutionContext sealed :
 ISerializable
/** @attribute SerializableAttribute() */ 
public final class ExecutionContext implements
 ISerializable
SerializableAttribute 
public final class ExecutionContext implements
 ISerializable
解説解説

ExecutionContext クラスは、実行論理スレッド関連するすべての情報に対して単一コンテナ提供します。この情報には、セキュリティ コンテキスト呼び出しコンテキスト同期コンテキストローカリゼーション コンテキスト、およびトランザクション コンテキスト含まれます。

ExecutionContext クラスは、ユーザー コードでこのコンテキストキャプチャしてユーザー定義の非同期ポイント間を転送する機能提供します共通言語ランタイムにより、マネージ プロセス実行時定義される非同期ポイント間で ExecutionContext一貫して転送されるようになります

実行コンテキストは、COM アパートメントマネージ バージョンです。アプリケーション ドメイン内では、スレッド転送するたびに実行コンテキスト全体転送する必要があります。この状況は、Thread.Start メソッド、ほとんどのスレッド プール操作Windows メッセージ ポンプ経由Windows フォームスレッド マーシャリングによる転送中に発生します圧縮スタック転送しない安全でないスレッド プール操作 (UnsafeQueueUserWorkItem メソッドなど) では、この状況発生しません。圧縮スタックフローする場合は、マネージ プリンシパル同期ロケール、およびユーザー コンテキストフローます。ExecutionContext クラスは、実行コンテキスト取得するための Capture メソッドおよび CreateCopy メソッド、および現在のスレッドに対して実行コンテキスト設定するための Run メソッド提供します

あるスレッド関連付けられた ExecutionContext を他のスレッド設定することはできません。この操作試行すると、例外スローさます。スレッド間で ExecutionContext反映させるには、ExecutionContextコピー作成します

ExecutionContext は、LogicalCallContext に関連付けられたすべてのデータ内部的に格納しますその結果ExecutionContextコピーして転送するときに LogicalCallContext データ反映できます

使用例使用例

ExecutionContext クラスメンバ使用する方法次のコード例示します

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
            Console.WriteLine("Executing the Main in the primary
 thread.")
            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.
            Dim aFC As AsyncFlowControl = ExecutionContext.SuppressFlow()
            Dim t1 As New
 Thread(New ThreadStart(AddressOf 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()))
            Dim t2 As New
 Thread(New ThreadStart(AddressOf DemandPermission))
            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(New ThreadStart(AddressOf DemandPermission))
            t3.Start()
            t3.Join()
            ' Show the Deny is again active.
            Dim t4 As New
 Thread(New ThreadStart(AddressOf DemandPermission))
            t4.Start()
            t4.Join()
            ' 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("In the thread executing a Demand
 for FileDialogPermission.")
            Dim fDP As New
 FileDialogPermission(FileDialogPermissionAccess.OpenSave)
            fDP.Demand()
            Console.WriteLine("Successfully demanded FileDialogPermission.")
        Catch e As Exception
            Console.WriteLine(e.Message)
        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(("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

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 'ToDo: Add
 Implements Clauses for implementation methods of these interface(s)
    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
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
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「ExecutionContext クラス」の関連用語

ExecutionContext クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



ExecutionContext クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS