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
[System.Runtime.InteropServices.ComVisible(true)]
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
public sealed class Thread : System.Runtime.ConstrainedExecution.CriticalFinalizerObject
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
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
type Thread = class
    inherit CriticalFinalizerObject
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
属性
実装

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

// [C++]
// Compile using /clr option.
using namespace System;
using namespace System::Threading;

// Simple threading scenario:  Start a Shared method running
// on a second thread.
public ref class ThreadExample
{
public:

   // 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.
   static void ThreadProc()
   {
      for ( int i = 0; i < 10; i++ )
      {
         Console::Write(  "ThreadProc: " );
         Console::WriteLine( i );
         
         // Yield the rest of the time slice.
         Thread::Sleep( 0 );

      }
   }

};

int main()
{
   Console::WriteLine( "Main thread: Start a second thread." );
   
   // Create the thread, passing a ThreadStart delegate that
   // represents the ThreadExample::ThreadProc method.  For a 
   // delegate representing a static method, no object is
   // required.
   Thread^ oThread = gcnew Thread( gcnew ThreadStart( &ThreadExample::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 oThread->Start() to see the difference.
   oThread->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." );
   oThread->Join();
   Console::WriteLine(  "Main thread: ThreadProc.Join has returned.  Press Enter to end program." );
   Console::ReadLine();
   return 0;
}
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();
    }
}
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.  

注釈

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

このセクションの内容

スレッドの開始
Thread オブジェクトの取得
フォアグラウンドスレッドとバックグラウンドスレッド
カルチャとスレッド
スレッドに関する情報の取得と制御

スレッドの開始

スレッドを開始するには、スレッドがクラス コンストラクターで実行するメソッドを表すデリゲートを指定します。 次に、 メソッドを 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
    
    Imports System.Diagnostics
    Imports System.Threading
    
    Module Example
       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
    
    Imports System.Diagnostics
    Imports System.Threading
    
    Module Example
       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 保持する必要はありません。 スレッドプロシージャが完了するまで、スレッドは引き続き実行されます。

Thread オブジェクトの取得

静的 (Shared Visual Basic では ) 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
Imports System.Threading

Module Example
   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<TResult> クラスをTask使用して、タスクベースの非同期パターンを実装します。

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

プロパティをいつでも設定することで、バックグラウンドで実行するスレッドを 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...
Imports System.Diagnostics
Imports System.Threading

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

重要

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

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

重要

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

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

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

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

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

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

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

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

    注意

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

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

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

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

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

コンストラクター

Thread(ParameterizedThreadStart)

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

Thread(ParameterizedThreadStart, Int32)

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

Thread(ThreadStart)

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

Thread(ThreadStart, Int32)

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

プロパティ

ApartmentState
互換性のために残されています。
互換性のために残されています。
互換性のために残されています。

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

CurrentContext

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

CurrentCulture

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

CurrentPrincipal

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

CurrentThread

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

CurrentUICulture

実行時にカルチャ固有のリソースを検索するためにリソース マネージャーで使用される、現在のカルチャを取得または設定します。

ExecutionContext

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

IsAlive

現在のスレッドの実行ステータスを示す値を取得します。

IsBackground

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

IsThreadPoolThread

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

ManagedThreadId

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

Name

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

Priority

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

ThreadState

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

メソッド

Abort()
互換性のために残されています。

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

Abort(Object)
互換性のために残されています。

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

AllocateDataSlot()

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

AllocateNamedDataSlot(String)

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

BeginCriticalRegion()

スレッドの中止または処理されない例外の影響によりアプリケーション ドメイン内の他のタスクが悪影響を受ける可能性があるコード領域に実行が入ることをホストに通知します。

BeginThreadAffinity()

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

DisableComObjectEagerCleanup()

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

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)

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

適用対象

スレッド セーフ

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

こちらもご覧ください