Thread クラス

定義

スレッドを作成および制御し、その優先順位を設定し、その状態を取得します。

public ref class Thread sealed : System::Runtime::ConstrainedExecution::CriticalFinalizerObject
public ref class Thread sealed
public ref class Thread sealed : System::Runtime::InteropServices::_Thread
public ref class Thread sealed : System::Runtime::ConstrainedExecution::CriticalFinalizerObject, System::Runtime::InteropServices::_Thread
public sealed class Thread : System.Runtime.ConstrainedExecution.CriticalFinalizerObject
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Thread
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
public sealed class Thread : System.Runtime.InteropServices._Thread
[System.Runtime.InteropServices.ComVisible(true)]
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
public sealed class Thread : System.Runtime.ConstrainedExecution.CriticalFinalizerObject, System.Runtime.InteropServices._Thread
type Thread = class
    inherit CriticalFinalizerObject
[<System.Runtime.InteropServices.ComVisible(true)>]
type Thread = class
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
type Thread = class
    interface _Thread
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
type Thread = class
    inherit CriticalFinalizerObject
    interface _Thread
Public NotInheritable Class Thread
Inherits CriticalFinalizerObject
Public NotInheritable Class Thread
Public NotInheritable Class Thread
Implements _Thread
Public NotInheritable Class Thread
Inherits CriticalFinalizerObject
Implements _Thread
継承
継承
Thread
属性
実装

次の例は、単純なスレッド機能を示しています。

using System;
using System.Threading;

// Simple threading scenario:  Start a static method running
// on a second thread.
public class ThreadExample {
    // The ThreadProc method is called when the thread starts.
    // It loops ten times, writing to the console and yielding
    // the rest of its time slice each time, and then ends.
    public static void ThreadProc() {
        for (int i = 0; i < 10; i++) {
            Console.WriteLine("ThreadProc: {0}", i);
            // Yield the rest of the time slice.
            Thread.Sleep(0);
        }
    }

    public static void Main() {
        Console.WriteLine("Main thread: Start a second thread.");
        // The constructor for the Thread class requires a ThreadStart
        // delegate that represents the method to be executed on the
        // thread.  C# simplifies the creation of this delegate.
        Thread t = new Thread(new ThreadStart(ThreadProc));

        // Start ThreadProc.  Note that on a uniprocessor, the new
        // thread does not get any processor time until the main thread
        // is preempted or yields.  Uncomment the Thread.Sleep that
        // follows t.Start() to see the difference.
        t.Start();
        //Thread.Sleep(0);

        for (int i = 0; i < 4; i++) {
            Console.WriteLine("Main thread: Do some work.");
            Thread.Sleep(0);
        }

        Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
        t.Join();
        Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.");
        Console.ReadLine();
    }
}
open System.Threading

// Simple threading scenario:  Start a static method running
// on a second thread.

// The ThreadProc method is called when the thread starts.
// It loops ten times, writing to the console and yielding
// the rest of its time slice each time, and then ends.
let threadProc () =
    for i = 0 to 9 do
        printfn $"ThreadProc: {i}"
        // Yield the rest of the time slice.
        Thread.Sleep 0

printfn "Main thread: Start a second thread."
// The constructor for the Thread class requires a ThreadStart
// delegate that represents the method to be executed on the
// thread. F# simplifies the creation of this delegate.
let t = Thread threadProc

// Start ThreadProc.  Note that on a uniprocessor, the new
// thread does not get any processor time until the main thread
// is preempted or yields.  Uncomment the Thread.Sleep that
// follows t.Start() to see the difference.
t.Start()
//Thread.Sleep 0

for _ = 0 to 3 do
    printfn "Main thread: Do some work."
    Thread.Sleep 0

printfn "Main thread: Call Join(), to wait until ThreadProc ends."
t.Join()
printfn "Main thread: ThreadProc.Join has returned.  Press Enter to end program."
stdin.ReadLine() |> ignore
Imports System.Threading

' Simple threading scenario:  Start a Shared method running
' on a second thread.
Public Class ThreadExample
    ' The ThreadProc method is called when the thread starts.
    ' It loops ten times, writing to the console and yielding 
    ' the rest of its time slice each time, and then ends.
    Public Shared Sub ThreadProc()
        Dim i As Integer
        For i = 0 To 9
            Console.WriteLine("ThreadProc: {0}", i)
            ' Yield the rest of the time slice.
            Thread.Sleep(0)
        Next
    End Sub

    Public Shared Sub Main()
        Console.WriteLine("Main thread: Start a second thread.")
        ' The constructor for the Thread class requires a ThreadStart 
        ' delegate.  The Visual Basic AddressOf operator creates this
        ' delegate for you.
        Dim t As New Thread(AddressOf ThreadProc)

        ' Start ThreadProc.  Note that on a uniprocessor, the new 
        ' thread does not get any processor time until the main thread 
        ' is preempted or yields.  Uncomment the Thread.Sleep that 
        ' follows t.Start() to see the difference.
        t.Start()
        'Thread.Sleep(0)

        Dim i As Integer
        For i = 1 To 4
            Console.WriteLine("Main thread: Do some work.")
            Thread.Sleep(0)
        Next

        Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.")
        t.Join()
        Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.")
        Console.ReadLine()
    End Sub
End Class

このコードでは、次のような出力が生成されます。

[VB, C++, C#]
Main thread: Start a second thread.
Main thread: Do some work.
ThreadProc: 0
Main thread: Do some work.
ThreadProc: 1
Main thread: Do some work.
ThreadProc: 2
Main thread: Do some work.
ThreadProc: 3
Main thread: Call Join(), to wait until ThreadProc ends.
ThreadProc: 4
ThreadProc: 5
ThreadProc: 6
ThreadProc: 7
ThreadProc: 8
ThreadProc: 9
Main thread: ThreadProc.Join has returned. Press Enter to end program.

注釈

Thread クラスは、スレッドを作成および制御し、その優先順位を設定し、その状態を取得します。

プロセスが開始されると、共通言語ランタイムによって、アプリケーション コードを実行する単一のフォアグラウンド スレッドが自動的に作成されます。 このメイン フォアグラウンド スレッドと共に、プロセスは 1 つ以上のスレッドを作成して、プロセスに関連付けられているプログラム コードの一部を実行できます。 これらのスレッドは、フォアグラウンドまたはバックグラウンドで実行できます。 さらに、 ThreadPool クラスを使用して、共通言語ランタイムによって管理されるワーカー スレッドでコードを実行できます。

スレッドを開始する

スレッドを開始するには、スレッドがクラス コンストラクターで実行するメソッドを表すデリゲートを指定します。 次に、 Start メソッドを呼び出して実行を開始します。

Threadコンストラクターは、実行するメソッドに引数を渡すことができるかどうかに応じて、次の 2 つのデリゲート型のいずれかを受け取ることができます。

  • メソッドに引数がない場合は、 ThreadStart デリゲートをコンストラクターに渡します。 これには次の署名があります。

    public delegate void ThreadStart()
    
    Public Delegate Sub ThreadStart()
    

    次の例では、 ExecuteInForeground メソッドを実行するスレッドを作成して開始します。 このメソッドは、一部のスレッド プロパティに関する情報を表示し、ループを実行して 5 分の 1 の間一時停止し、経過した秒数を表示します。 スレッドが少なくとも 5 秒間実行されると、ループは終了し、スレッドは実行を終了します。

    using System;
    using System.Diagnostics;
    using System.Threading;
    
    public class Example
    {
       public static void Main()
       {
          var th = new Thread(ExecuteInForeground);
          th.Start();
          Thread.Sleep(1000);
          Console.WriteLine("Main thread ({0}) exiting...",
                            Thread.CurrentThread.ManagedThreadId);
       }
    
       private static void ExecuteInForeground()
       {
          var sw = Stopwatch.StartNew();
          Console.WriteLine("Thread {0}: {1}, Priority {2}",
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority);
          do {
             Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000.0);
             Thread.Sleep(500);
          } while (sw.ElapsedMilliseconds <= 5000);
          sw.Stop();
       }
    }
    // The example displays output like the following:
    //       Thread 3: Running, Priority Normal
    //       Thread 3: Elapsed 0.00 seconds
    //       Thread 3: Elapsed 0.51 seconds
    //       Main thread (1) exiting...
    //       Thread 3: Elapsed 1.02 seconds
    //       Thread 3: Elapsed 1.53 seconds
    //       Thread 3: Elapsed 2.05 seconds
    //       Thread 3: Elapsed 2.55 seconds
    //       Thread 3: Elapsed 3.07 seconds
    //       Thread 3: Elapsed 3.57 seconds
    //       Thread 3: Elapsed 4.07 seconds
    //       Thread 3: Elapsed 4.58 seconds
    
    open System.Diagnostics
    open System.Threading
    
    let executeInForeground () =
        let sw = Stopwatch.StartNew()
    
        printfn $"Thread {Thread.CurrentThread.ManagedThreadId}: {Thread.CurrentThread.ThreadState}, Priority {Thread.CurrentThread.Priority}"
    
        while sw.ElapsedMilliseconds <= 5000 do
            printfn $"Thread {Thread.CurrentThread.ManagedThreadId}: Elapsed {sw.ElapsedMilliseconds / 1000L:N2} seconds"
            Thread.Sleep 500
    
        sw.Stop()
    
    let th = Thread executeInForeground
    th.Start()
    Thread.Sleep 1000
    printfn $"Main thread ({Thread.CurrentThread.ManagedThreadId}) exiting..."
    
    // The example displays output like the following:
    //       Thread 3: Running, Priority Normal
    //       Thread 3: Elapsed 0.00 seconds
    //       Thread 3: Elapsed 0.51 seconds
    //       Main thread (1) exiting...
    //       Thread 3: Elapsed 1.02 seconds
    //       Thread 3: Elapsed 1.53 seconds
    //       Thread 3: Elapsed 2.05 seconds
    //       Thread 3: Elapsed 2.55 seconds
    //       Thread 3: Elapsed 3.07 seconds
    //       Thread 3: Elapsed 3.57 seconds
    //       Thread 3: Elapsed 4.07 seconds
    //       Thread 3: Elapsed 4.58 seconds
    
    Imports System.Diagnostics
    Imports System.Threading
    
    Module Example3
        Public Sub Main()
            Dim th As New Thread(AddressOf ExecuteInForeground)
            th.Start()
            Thread.Sleep(1000)
            Console.WriteLine("Main thread ({0}) exiting...", Thread.CurrentThread.ManagedThreadId)
        End Sub
    
        Private Sub ExecuteInForeground()
            Dim start As DateTime = DateTime.Now
            Dim sw As Stopwatch = Stopwatch.StartNew()
            Console.WriteLine("Thread {0}: {1}, Priority {2}",
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority)
            Do
                Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000)
                Thread.Sleep(500)
            Loop While sw.ElapsedMilliseconds <= 5000
            sw.Stop()
        End Sub
    End Module
    ' The example displays output like the following:
    '       Thread 3: Running, Priority Normal
    '       Thread 3: Elapsed 0.00 seconds
    '       Thread 3: Elapsed 0.51 seconds
    '       Main thread (1) exiting...
    '       Thread 3: Elapsed 1.02 seconds
    '       Thread 3: Elapsed 1.53 seconds
    '       Thread 3: Elapsed 2.05 seconds
    '       Thread 3: Elapsed 2.55 seconds
    '       Thread 3: Elapsed 3.07 seconds
    '       Thread 3: Elapsed 3.57 seconds
    '       Thread 3: Elapsed 4.07 seconds
    '       Thread 3: Elapsed 4.58 seconds
    
  • メソッドに引数がある場合は、 ParameterizedThreadStart デリゲートをコンストラクターに渡します。 これには次の署名があります。

    public delegate void ParameterizedThreadStart(object obj)
    
    Public Delegate Sub ParameterizedThreadStart(obj As Object)
    

    デリゲートによって実行されるメソッドは、(C# で) キャストしたり、パラメーターを適切な型に (Visual Basic で) 変換したりできます。

    次の例は、 Thread(ParameterizedThreadStart) コンストラクターを呼び出す点を除き、前の例と同じです。 このバージョンの ExecuteInForeground メソッドには、ループが実行されるおおよそのミリ秒数を表す 1 つのパラメーターがあります。

    using System;
    using System.Diagnostics;
    using System.Threading;
    
    public class Example
    {
       public static void Main()
       {
          var th = new Thread(ExecuteInForeground);
          th.Start(4500);
          Thread.Sleep(1000);
          Console.WriteLine("Main thread ({0}) exiting...",
                            Thread.CurrentThread.ManagedThreadId);
       }
    
       private static void ExecuteInForeground(Object obj)
       {
          int interval;
          try {
             interval = (int) obj;
          }
          catch (InvalidCastException) {
             interval = 5000;
          }
          var sw = Stopwatch.StartNew();
          Console.WriteLine("Thread {0}: {1}, Priority {2}",
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority);
          do {
             Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000.0);
             Thread.Sleep(500);
          } while (sw.ElapsedMilliseconds <= interval);
          sw.Stop();
       }
    }
    // The example displays output like the following:
    //       Thread 3: Running, Priority Normal
    //       Thread 3: Elapsed 0.00 seconds
    //       Thread 3: Elapsed 0.52 seconds
    //       Main thread (1) exiting...
    //       Thread 3: Elapsed 1.03 seconds
    //       Thread 3: Elapsed 1.55 seconds
    //       Thread 3: Elapsed 2.06 seconds
    //       Thread 3: Elapsed 2.58 seconds
    //       Thread 3: Elapsed 3.09 seconds
    //       Thread 3: Elapsed 3.61 seconds
    //       Thread 3: Elapsed 4.12 seconds
    
    open System
    open System.Diagnostics
    open System.Threading
    
    let executeInForeground obj =
        let interval =
            try
                unbox<int> obj
            with :? InvalidCastException ->
                5000
    
        let sw = Stopwatch.StartNew()
    
        printfn $"Thread {Thread.CurrentThread.ManagedThreadId}: {Thread.CurrentThread.ThreadState}, Priority {Thread.CurrentThread.Priority}"
    
        while sw.ElapsedMilliseconds <= interval do
            printfn $"Thread {Thread.CurrentThread.ManagedThreadId}: Elapsed {sw.ElapsedMilliseconds / 1000L:N2} seconds"
            Thread.Sleep 500
    
        sw.Stop()
    
    let th = Thread(ParameterizedThreadStart executeInForeground)
    th.Start 4500
    Thread.Sleep 1000
    printfn $"Main thread ({Thread.CurrentThread.ManagedThreadId}) exiting..."
    
    // The example displays output like the following:
    //       Thread 3: Running, Priority Normal
    //       Thread 3: Elapsed 0.00 seconds
    //       Thread 3: Elapsed 0.52 seconds
    //       Main thread (1) exiting...
    //       Thread 3: Elapsed 1.03 seconds
    //       Thread 3: Elapsed 1.55 seconds
    //       Thread 3: Elapsed 2.06 seconds
    //       Thread 3: Elapsed 2.58 seconds
    //       Thread 3: Elapsed 3.09 seconds
    //       Thread 3: Elapsed 3.61 seconds
    //       Thread 3: Elapsed 4.12 seconds
    
    Imports System.Diagnostics
    Imports System.Threading
    
    Module Example4
        Public Sub Main()
            Dim th As New Thread(AddressOf ExecuteInForeground)
            th.Start(4500)
            Thread.Sleep(1000)
            Console.WriteLine("Main thread ({0}) exiting...", Thread.CurrentThread.ManagedThreadId)
        End Sub
    
        Private Sub ExecuteInForeground(obj As Object)
            Dim interval As Integer
            If IsNumeric(obj) Then
                interval = CInt(obj)
            Else
                interval = 5000
            End If
            Dim start As DateTime = DateTime.Now
            Dim sw As Stopwatch = Stopwatch.StartNew()
            Console.WriteLine("Thread {0}: {1}, Priority {2}",
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority)
            Do
                Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000)
                Thread.Sleep(500)
            Loop While sw.ElapsedMilliseconds <= interval
            sw.Stop()
        End Sub
    End Module
    ' The example displays output like the following:
    '       Thread 3: Running, Priority Normal
    '       Thread 3: Elapsed 0.00 seconds
    '       Thread 3: Elapsed 0.52 seconds
    '       Main thread (1) exiting...
    '       Thread 3: Elapsed 1.03 seconds
    '       Thread 3: Elapsed 1.55 seconds
    '       Thread 3: Elapsed 2.06 seconds
    '       Thread 3: Elapsed 2.58 seconds
    '       Thread 3: Elapsed 3.09 seconds
    '       Thread 3: Elapsed 3.61 seconds
    '       Thread 3: Elapsed 4.12 seconds
    

スレッドを開始したら、 Thread オブジェクトへの参照を保持する必要はありません。 スレッドプロシージャが完了するまで、スレッドは引き続き実行されます。

スレッド オブジェクトの取得

静的 (Visual Basic のShared ) CurrentThread プロパティを使用して、スレッドが実行しているコードから現在実行中のスレッドへの参照を取得できます。 次の例では、 CurrentThread プロパティを使用して、メイン アプリケーション スレッド、別のフォアグラウンド スレッド、バックグラウンド スレッド、スレッド プール スレッドに関する情報を表示します。

using System;
using System.Threading;

public class Example
{
   static Object obj = new Object();
   
   public static void Main()
   {
      ThreadPool.QueueUserWorkItem(ShowThreadInformation);
      var th1 = new Thread(ShowThreadInformation);
      th1.Start();
      var th2 = new Thread(ShowThreadInformation);
      th2.IsBackground = true;
      th2.Start();
      Thread.Sleep(500);
      ShowThreadInformation(null); 
   }
   
   private static void ShowThreadInformation(Object state)
   {
      lock (obj) {
         var th  = Thread.CurrentThread;
         Console.WriteLine("Managed thread #{0}: ", th.ManagedThreadId);
         Console.WriteLine("   Background thread: {0}", th.IsBackground);
         Console.WriteLine("   Thread pool thread: {0}", th.IsThreadPoolThread);
         Console.WriteLine("   Priority: {0}", th.Priority);
         Console.WriteLine("   Culture: {0}", th.CurrentCulture.Name);
         Console.WriteLine("   UI culture: {0}", th.CurrentUICulture.Name);
         Console.WriteLine();
      }   
   }
}
// The example displays output like the following:
//       Managed thread #6:
//          Background thread: True
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//       
//       Managed thread #3:
//          Background thread: True
//          Thread pool thread: True
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//       
//       Managed thread #4:
//          Background thread: False
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//       
//       Managed thread #1:
//          Background thread: False
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
open System.Threading

let obj = obj ()

let showThreadInformation (state: obj) =
    lock obj (fun () ->
        let th = Thread.CurrentThread
        printfn $"Managed thread #{th.ManagedThreadId}: "
        printfn $"   Background thread: {th.IsBackground}"
        printfn $"   Thread pool thread: {th.IsThreadPoolThread}"
        printfn $"   Priority: {th.Priority}"
        printfn $"   Culture: {th.CurrentCulture.Name}"
        printfn $"   UI culture: {th.CurrentUICulture.Name}"
        printfn "")

ThreadPool.QueueUserWorkItem showThreadInformation |> ignore
let th1 = Thread(ParameterizedThreadStart showThreadInformation)
th1.Start()
let th2 = Thread(ParameterizedThreadStart showThreadInformation)
th2.IsBackground <- true
th2.Start()
Thread.Sleep 500
showThreadInformation ()

// The example displays output like the following:
//       Managed thread #6:
//          Background thread: True
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//
//       Managed thread #3:
//          Background thread: True
//          Thread pool thread: True
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//
//       Managed thread #4:
//          Background thread: False
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//
//       Managed thread #1:
//          Background thread: False
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
Imports System.Threading

Module Example2
    Private lock As New Object()

    Public Sub Main()
        ThreadPool.QueueUserWorkItem(AddressOf ShowThreadInformation)
        Dim th1 As New Thread(AddressOf ShowThreadInformation)
        th1.Start()
        Dim th2 As New Thread(AddressOf ShowThreadInformation)
        th2.IsBackground = True
        th2.Start()
        Thread.Sleep(500)
        ShowThreadInformation(Nothing)
    End Sub

    Private Sub ShowThreadInformation(state As Object)
        SyncLock lock
            Dim th As Thread = Thread.CurrentThread
            Console.WriteLine("Managed thread #{0}: ", th.ManagedThreadId)
            Console.WriteLine("   Background thread: {0}", th.IsBackground)
            Console.WriteLine("   Thread pool thread: {0}", th.IsThreadPoolThread)
            Console.WriteLine("   Priority: {0}", th.Priority)
            Console.WriteLine("   Culture: {0}", th.CurrentCulture.Name)
            Console.WriteLine("   UI culture: {0}", th.CurrentUICulture.Name)
            Console.WriteLine()
        End SyncLock
    End Sub
End Module
' The example displays output like the following:
'       ' Managed thread #6:
'          Background thread: True
'          Thread pool thread: False
'          Priority: Normal
'          Culture: en-US
'          UI culture: en-US
'       
'       Managed thread #3:
'          Background thread: True
'          Thread pool thread: True
'          Priority: Normal
'          Culture: en-US
'          UI culture: en-US
'       
'       Managed thread #4:
'          Background thread: False
'          Thread pool thread: False
'          Priority: Normal
'          Culture: en-US
'          UI culture: en-US
'       
'       Managed thread #1:
'          Background thread: False
'          Thread pool thread: False
'          Priority: Normal
'          Culture: en-US
'          UI culture: en-US

フォアグラウンド スレッドとバックグラウンド スレッド

Thread クラスのインスタンスは、フォアグラウンド スレッドまたはバックグラウンド スレッドを表します。 バックグラウンド スレッドはフォアグラウンド スレッドと同じですが、1 つの例外があります。すべてのフォアグラウンド スレッドが終了した場合、バックグラウンド スレッドはプロセスを実行したままにしません。 すべてのフォアグラウンド スレッドが停止されると、ランタイムはすべてのバックグラウンド スレッドを停止し、シャットダウンします。

既定では、次のスレッドがフォアグラウンドで実行されます。

  • メイン アプリケーション スレッド。

  • Thread クラス コンストラクターを呼び出すことによって作成されたすべてのスレッド。

既定では、次のスレッドがバックグラウンドで実行されます。

  • スレッド プール スレッド。これは、ランタイムが管理するワーカー スレッドのプールから取得されます。 ThreadPool クラスを使用して、スレッド プールを構成し、スレッド プール スレッドの作業をスケジュールできます。

    Note

    タスク ベースの非同期操作は、スレッド プール スレッドで自動的に実行されます。 タスク ベースの非同期操作では、 Task クラスと Task<TResult> クラスを使用して 、タスク ベースの非同期パターンを実装します。

  • アンマネージド コードからマネージド実行環境に入るすべてのスレッド。

IsBackground プロパティをいつでも設定することで、バックグラウンドで実行するスレッドを変更できます。 バックグラウンド スレッドは、アプリケーションが実行されている限り続行する必要があるが、ファイル システムの変更や受信ソケット接続の監視など、アプリケーションの終了を妨げるべきではない操作に役立ちます。

次の例は、フォアグラウンド スレッドとバックグラウンド スレッドの違いを示しています。 これは、 スレッドを開始 する前にバックグラウンドで実行するようにスレッドを設定する点を除いて、「スレッドの開始」セクションの最初の例に似ています。 出力が示すように、ループは 5 秒間実行される前に中断されます。

using System;
using System.Diagnostics;
using System.Threading;

public class Example
{
   public static void Main()
   {
      var th = new Thread(ExecuteInForeground);
      th.IsBackground = true;
      th.Start();
      Thread.Sleep(1000);
      Console.WriteLine("Main thread ({0}) exiting...",
                        Thread.CurrentThread.ManagedThreadId);
   }

   private static void ExecuteInForeground()
   {
      var sw = Stopwatch.StartNew();
      Console.WriteLine("Thread {0}: {1}, Priority {2}",
                        Thread.CurrentThread.ManagedThreadId,
                        Thread.CurrentThread.ThreadState,
                        Thread.CurrentThread.Priority);
      do {
         Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
                           Thread.CurrentThread.ManagedThreadId,
                           sw.ElapsedMilliseconds / 1000.0);
         Thread.Sleep(500);
      } while (sw.ElapsedMilliseconds <= 5000);
      sw.Stop();
   }
}
// The example displays output like the following:
//       Thread 3: Background, Priority Normal
//       Thread 3: Elapsed 0.00 seconds
//       Thread 3: Elapsed 0.51 seconds
//       Main thread (1) exiting...
open System.Diagnostics
open System.Threading

let executeInForeground () =
    let sw = Stopwatch.StartNew()
    printfn $"Thread {Thread.CurrentThread.ManagedThreadId}: {Thread.CurrentThread.ThreadState}, Priority {Thread.CurrentThread.Priority}"
    while sw.ElapsedMilliseconds <= 5000 do
        printfn $"Thread {Thread.CurrentThread.ManagedThreadId}: Elapsed {sw.ElapsedMilliseconds / 1000L:N2} seconds"
        Thread.Sleep 500
    sw.Stop()

let th = Thread executeInForeground
th.IsBackground <- true
th.Start()
Thread.Sleep 1000
printfn $"Main thread ({Thread.CurrentThread.ManagedThreadId}) exiting..."

// The example displays output like the following:
//       Thread 3: Background, Priority Normal
//       Thread 3: Elapsed 0.00 seconds
//       Thread 3: Elapsed 0.51 seconds
//       Main thread (1) exiting...
Imports System.Diagnostics
Imports System.Threading

Module Example1
    Public Sub Main()
        Dim th As New Thread(AddressOf ExecuteInForeground)
        th.IsBackground = True
        th.Start()
        Thread.Sleep(1000)
        Console.WriteLine("Main thread ({0}) exiting...", Thread.CurrentThread.ManagedThreadId)
    End Sub

    Private Sub ExecuteInForeground()
        Dim start As DateTime = DateTime.Now
        Dim sw As Stopwatch = Stopwatch.StartNew()
        Console.WriteLine("Thread {0}: {1}, Priority {2}",
                        Thread.CurrentThread.ManagedThreadId,
                        Thread.CurrentThread.ThreadState,
                        Thread.CurrentThread.Priority)
        Do
            Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds",
                           Thread.CurrentThread.ManagedThreadId,
                           sw.ElapsedMilliseconds / 1000)
            Thread.Sleep(500)
        Loop While sw.ElapsedMilliseconds <= 5000
        sw.Stop()
    End Sub
End Module
' The example displays output like the following:
'       Thread 3: Background, Priority Normal
'       Thread 3: Elapsed 0.00 seconds
'       Thread 3: Elapsed 0.51 seconds
'       Main thread (1) exiting...

カルチャとスレッド

各スレッドには、 CurrentCulture プロパティで表されるカルチャと、 CurrentUICulture プロパティで表される UI カルチャがあります。 現在のカルチャは、解析と書式設定、文字列比較、並べ替えなどのカルチャに依存する操作をサポートし、スレッドによって使用される書き込みシステムとカレンダーも制御します。 現在の UI カルチャでは、リソース ファイル内のリソースをカルチャに依存して取得できます。

Important

CurrentCultureプロパティとCurrentUICulture プロパティは、現在のスレッド以外のスレッドで使用すると、確実に動作しません。 スレッドが別のスレッドでこれらのプロパティの読み取りまたは書き込みを試みると、 InvalidOperationException がスローされます。 現在のカルチャを取得して設定するには、 CultureInfo.CurrentCulture プロパティと CultureInfo.CurrentUICulture プロパティを使用することをお勧めします。

新しいスレッドがインスタンス化されると、そのカルチャと UI カルチャは、新しいスレッドが作成されるスレッドのカルチャと UI カルチャではなく、現在のシステム カルチャと UI カルチャによって定義されます。 つまり、たとえば、現在のシステム カルチャが英語 (米国) で、プライマリ アプリケーション スレッドの現在のカルチャがフランス語 (フランス) の場合、プライマリ スレッドから Thread(ParameterizedThreadStart) コンストラクターを呼び出すことによって作成される新しいスレッドのカルチャは、フランス語 (フランス) ではなく英語 (米国) になります。 詳細については、 CultureInfo クラストピックの「カルチャとスレッド」セクションを参照してください。

Important

これは、.NET Framework 4.6 以降のバージョンを対象とするアプリに対して非同期操作を実行するスレッドには当てはまりません。 この場合、カルチャと UI カルチャは非同期操作のコンテキストの一部です。非同期操作が既定で実行されるスレッドは、非同期操作が起動されたスレッドのカルチャと UI カルチャを継承します。 詳細については、 CultureInfo クラスの解説の「カルチャとタスクベースの非同期操作」セクションを参照してください。

アプリケーションで実行されているすべてのスレッドが同じカルチャと UI カルチャを共有するように、次のいずれかの操作を実行できます。

詳細と例については、 CultureInfo クラスの解説の「カルチャとスレッド」セクションを参照してください。

スレッドに関する情報の取得と制御

スレッドに関する情報を提供する多数のプロパティ値を取得できます。 場合によっては、これらのプロパティ値を設定してスレッドの操作を制御することもできます。 これらのスレッド プロパティには、次のものがあります。

  • 名前。 Name は、スレッドを識別するために使用できる write-once プロパティです。 既定値は null です。

  • GetHashCode メソッドを呼び出して取得できるハッシュ コード。 ハッシュ コードは、スレッドを一意に識別するために使用できます。スレッドの有効期間中、値を取得するアプリケーション ドメインに関係なく、そのハッシュ コードは他のスレッドの値と競合しません。

  • スレッド ID。 読み取り専用 ManagedThreadId プロパティの値はランタイムによって割り当てられ、そのプロセス内のスレッドを一意に識別します。

    Note

    アンマネージド ホストはマネージド スレッドとアンマネージド スレッドの間のリレーションシップを制御できるため、オペレーティング システム の ThreadId はマネージド スレッドとの固定関係を持っていません。 具体的には、高度なホストでは、 CLR ホスティング API を使用して、同じオペレーティング システム スレッドに対して多数のマネージド スレッドをスケジュールしたり、異なるオペレーティング システム スレッド間でマネージド スレッドを移動したりできます。

  • スレッドの現在の状態。 スレッドが存在する間、スレッドは常に、 ThreadState プロパティによって定義された 1 つ以上の状態にあります。

  • スケジュールの優先順位レベル。 ThreadPriority プロパティによって定義されます。 スレッドの優先度を要求するようにこの値を設定することはできますが、オペレーティング システムによって優先される保証はありません。

  • 読み取り専用 IsThreadPoolThread プロパティ。スレッドがスレッド プール スレッドであるかどうかを示します。

  • IsBackground プロパティ。 詳細については、「 フォアグラウンド スレッドとバックグラウンド スレッド 」セクションを参照してください。

コンストラクター

名前 説明
Thread(ParameterizedThreadStart, Int32)

スレッドの開始時にオブジェクトをスレッドに渡すデリゲートを指定し、スレッドの最大スタック サイズを指定して、 Thread クラスの新しいインスタンスを初期化します。

Thread(ParameterizedThreadStart)

スレッドの開始時にオブジェクトをスレッドに渡すデリゲートを指定して、 Thread クラスの新しいインスタンスを初期化します。

Thread(ThreadStart, Int32)

スレッドの最大スタック サイズを指定して、 Thread クラスの新しいインスタンスを初期化します。

Thread(ThreadStart)

Thread クラスの新しいインスタンスを初期化します。

プロパティ

名前 説明
ApartmentState
古い.
古い.

このスレッドのアパートメント状態を取得または設定します。

CurrentContext

スレッドが実行されている現在のコンテキストを取得します。

CurrentCulture

現在のスレッドのカルチャを取得または設定します。

CurrentPrincipal

スレッドの現在のプリンシパル (ロールベースのセキュリティ用) を取得または設定します。

CurrentThread

現在実行中のスレッドを取得します。

CurrentUICulture

実行時にカルチャ固有のリソースを検索するために Resource Manager によって使用される現在のカルチャを取得または設定します。

ExecutionContext

現在のスレッドのさまざまなコンテキストに関する情報を含む ExecutionContext オブジェクトを取得します。

IsAlive

現在のスレッドの実行状態を示す値を取得します。

IsBackground

スレッドがバックグラウンド スレッドかどうかを示す値を取得または設定します。

IsThreadPoolThread

スレッドがマネージド スレッド プールに属しているかどうかを示す値を取得します。

ManagedThreadId

現在のマネージド スレッドの一意識別子を取得します。

Name

スレッドの名前を取得または設定します。

Priority

スレッドのスケジュールの優先順位を示す値を取得または設定します。

ThreadState

現在のスレッドの状態を含む値を取得します。

メソッド

名前 説明
Abort()
古い.

スレッドが呼び出されたスレッドで ThreadAbortException を発生させ、スレッドを終了するプロセスを開始します。 通常、このメソッドを呼び出すとスレッドが終了します。

Abort(Object)
古い.

スレッドが呼び出されたスレッドで ThreadAbortException を発生させ、スレッド終了に関する例外情報も提供しながら、スレッドを終了するプロセスを開始します。 通常、このメソッドを呼び出すとスレッドが終了します。

AllocateDataSlot()

すべてのスレッドに名前のないデータ スロットを割り当てます。 パフォーマンスを向上させるには、代わりに ThreadStaticAttribute 属性でマークされているフィールドを使用します。

AllocateNamedDataSlot(String)

すべてのスレッドに名前付きデータ スロットを割り当てます。 パフォーマンスを向上させるには、代わりに ThreadStaticAttribute 属性でマークされているフィールドを使用します。

BeginCriticalRegion()

スレッドの中止またはハンドルされない例外の影響がアプリケーション ドメイン内の他のタスクを危険にさらす可能性があるコード領域を入力しようとしていることをホストに通知します。

BeginThreadAffinity()

マネージド コードが現在の物理オペレーティング システム スレッドの ID に依存する命令を実行しようとしていることをホストに通知します。

DisableComObjectEagerCleanup()

現在のスレッドのランタイム呼び出し可能ラッパー (RCW) の自動クリーンアップをオフにします。

EndCriticalRegion()

スレッドの中止またはハンドルされない例外の影響が現在のタスクに制限されているコード領域を入力しようとしていることをホストに通知します。

EndThreadAffinity()

マネージド コードが現在の物理オペレーティング システム スレッドの ID に依存する命令の実行を完了したことをホストに通知します。

Equals(Object)

指定したオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
Finalize()

ガベージ コレクターが Thread オブジェクトを再利用するときに、リソースが解放され、その他のクリーンアップ操作が実行されるようにします。

FreeNamedDataSlot(String)

プロセス内のすべてのスレッドについて、名前とスロットの間の関連付けを削除します。 パフォーマンスを向上させるには、代わりに ThreadStaticAttribute 属性でマークされているフィールドを使用します。

GetApartmentState()

アパートメントの状態を示す ApartmentState 値を返します。

GetCompressedStack()
古い.
古い.

現在のスレッドのスタックをキャプチャするために使用できる CompressedStack オブジェクトを返します。

GetCurrentProcessorId()

現在のスレッドが実行しているプロセッサを示すために使用される ID を取得します。

GetData(LocalDataStoreSlot)

現在のスレッドの現在のドメイン内で、現在のスレッドの指定されたスロットから値を取得します。 パフォーマンスを向上させるには、代わりに ThreadStaticAttribute 属性でマークされているフィールドを使用します。

GetDomain()

現在のスレッドが実行されている現在のドメインを返します。

GetDomainID()

一意のアプリケーション ドメイン識別子を返します。

GetHashCode()

現在のスレッドのハッシュ コードを返します。

GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetNamedDataSlot(String)

名前付きデータ スロットを検索します。 パフォーマンスを向上させるには、代わりに ThreadStaticAttribute 属性でマークされているフィールドを使用します。

GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
Interrupt()

WaitSleepJoin スレッド状態のスレッドを中断します。

Join()

このインスタンスによって表されるスレッドが終了するまで呼び出し元のスレッドをブロックし、標準の COM と SendMessage ポンプを引き続き実行します。

Join(Int32)

このインスタンスによって表されるスレッドが終了するか、指定された時間が経過するまで呼び出し元のスレッドをブロックします。一方で、標準の COM および SendMessage ポンプを引き続き実行します。

Join(TimeSpan)

このインスタンスによって表されるスレッドが終了するか、指定された時間が経過するまで呼び出し元のスレッドをブロックします。一方で、標準の COM および SendMessage ポンプを引き続き実行します。

MemberwiseClone()

現在の Objectの簡易コピーを作成します。

(継承元 Object)
MemoryBarrier()

メモリ アクセスを次のように同期します。現在のスレッドを実行しているプロセッサは、MemoryBarrier()の呼び出しに続くメモリ アクセス後に実行MemoryBarrier()呼び出しの前にメモリがアクセスするように命令を並べ替えることはできません。

ResetAbort()
古い.

現在のスレッドに対して要求された Abort(Object) を取り消します。

Resume()
古い.
古い.
古い.

中断されたスレッドを再開します。

SetApartmentState(ApartmentState)

スレッドが開始される前のアパートメント状態を設定します。

SetCompressedStack(CompressedStack)
古い.
古い.

キャプチャされた CompressedStack を現在のスレッドに適用します。

SetData(LocalDataStoreSlot, Object)

そのスレッドの現在のドメインに対して、現在実行中のスレッドの指定されたスロット内のデータを設定します。 パフォーマンスを向上させるには、代わりに ThreadStaticAttribute 属性でマークされたフィールドを使用してください。

Sleep(Int32)

指定したミリ秒単位で現在のスレッドを中断します。

Sleep(TimeSpan)

指定した時間、現在のスレッドを中断します。

SpinWait(Int32)

iterations パラメーターで定義された回数だけスレッドを待機させます。

Start()

オペレーティング システムが現在のインスタンスの状態を Runningに変更します。

Start(Object)

オペレーティング システムが現在のインスタンスの状態を Runningに変更し、必要に応じて、スレッドが実行するメソッドで使用されるデータを含むオブジェクトを提供します。

Suspend()
古い.
古い.
古い.

スレッドを中断するか、スレッドが既に中断されている場合は、効果はありません。

ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)
TrySetApartmentState(ApartmentState)

スレッドが開始される前のアパートメント状態を設定します。

UnsafeStart()

オペレーティング システムが現在のインスタンスの状態を Runningに変更します。

UnsafeStart(Object)

オペレーティング システムが現在のインスタンスの状態を Runningに変更し、必要に応じて、スレッドが実行するメソッドで使用されるデータを含むオブジェクトを提供します。

VolatileRead(Byte)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileRead(Double)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileRead(Int16)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileRead(Int32)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileRead(Int64)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileRead(IntPtr)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileRead(Object)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileRead(SByte)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileRead(Single)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileRead(UInt16)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileRead(UInt32)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileRead(UInt64)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileRead(UIntPtr)
古い.

フィールドの値を読み取ります。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの後に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの前に移動できません。

VolatileWrite(Byte, Byte)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

VolatileWrite(Double, Double)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

VolatileWrite(Int16, Int16)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

VolatileWrite(Int32, Int32)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

VolatileWrite(Int64, Int64)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

VolatileWrite(IntPtr, IntPtr)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

VolatileWrite(Object, Object)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

VolatileWrite(SByte, SByte)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

VolatileWrite(Single, Single)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

VolatileWrite(UInt16, UInt16)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

VolatileWrite(UInt32, UInt32)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

VolatileWrite(UInt64, UInt64)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

VolatileWrite(UIntPtr, UIntPtr)
古い.

フィールドに値を書き込みます。 必要なシステムでは、プロセッサがメモリ操作を並べ替えないようにするメモリ バリアを挿入します。コード内でこのメソッドの前に読み取りまたは書き込みが表示される場合、プロセッサはこのメソッドの後に移動できません。

Yield()

呼び出し元のスレッドから、現在のプロセッサ上で実行する準備が整っている別のスレッドに実行を切り替えます。 オペレーティング システムは、生成するスレッドを選択します。

明示的なインターフェイスの実装

名前 説明
_Thread.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

一連の名前を対応する一連のディスパッチ識別子に割り当てます。

_Thread.GetTypeInfo(UInt32, UInt32, IntPtr)

オブジェクトの型情報を取得します。この型情報を使用して、インターフェイスの型情報を取得できます。

_Thread.GetTypeInfoCount(UInt32)

オブジェクトが提供する型情報インターフェイスの数 (0 または 1) を取得します。

_Thread.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

オブジェクトによって公開されるプロパティとメソッドへのアクセスを提供します。

適用対象

スレッド セーフ

この型はスレッド セーフです。

こちらもご覧ください