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) メンバはすべて、スレッド セーフです。インスタンス メンバの場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

ExecutionContext メソッド


パブリック メソッドパブリック メソッド

  名前 説明
パブリック メソッド Capture 現在のスレッドから実行コンテキストをキャプチャします。
パブリック メソッド CreateCopy 現在の実行コンテキストのコピーを作成します。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。)
パブリック メソッド GetObjectData 現在の実行コンテキストのインスタンスを再作成するのに必要な論理コンテキスト情報を使用して、指定した SerializationInfo オブジェクトを設定します。
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 ( Object から継承されます。)
パブリック メソッド IsFlowSuppressed 実行コンテキストのフローが現在抑制されているかどうかを示します。
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。)
パブリック メソッド RestoreFlow 複数の非同期スレッド間における実行コンテキストのフローを復元します。
パブリック メソッド Run 現在のスレッドで指定した実行コンテキストを使用してメソッドを実行します。
パブリック メソッド SuppressFlow 複数の非同期スレッド間における実行コンテキストのフローを抑制します。
パブリック メソッド ToString  現在の Object を表す String を返します。 ( Object から継承されます。)
参照参照

関連項目

ExecutionContext クラス
System.Threading 名前空間

ExecutionContext メンバ

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

ExecutionContext データ型で公開されるメンバを以下の表に示します。


パブリック メソッドパブリック メソッド
  名前 説明
パブリック メソッド Capture 現在のスレッドから実行コンテキストをキャプチャします。
パブリック メソッド CreateCopy 現在の実行コンテキストのコピーを作成します。
パブリック メソッド Equals  オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。)
パブリック メソッド GetObjectData 現在の実行コンテキストのインスタンスを再作成するのに必要な論理コンテキスト情報を使用して、指定した SerializationInfo オブジェクトを設定します。
パブリック メソッド GetType  現在のインスタンスの Type を取得します。 (Object から継承されます。)
パブリック メソッド IsFlowSuppressed 実行コンテキストのフローが現在抑制されているかどうかを示します。
パブリック メソッド ReferenceEquals  指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。)
パブリック メソッド RestoreFlow 複数の非同期スレッド間における実行コンテキストのフローを復元します。
パブリック メソッド Run 現在のスレッドで指定した実行コンテキストを使用してメソッドを実行します。
パブリック メソッド SuppressFlow 複数の非同期スレッド間における実行コンテキストのフローを抑制します。
パブリック メソッド ToString  現在の Object を表す String を返します。 (Object から継承されます。)
参照参照

関連項目

ExecutionContext クラス
System.Threading 名前空間



英和和英テキスト翻訳

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

辞書ショートカット

すべての辞書の索引

「ExecutionContext」の関連用語

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

   

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



ExecutionContextのページの著作権

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

©2026 GRAS Group, Inc.RSS