Thread クラス
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
スレッドを作成および制御し、その優先順位の設定およびステータスの取得を実行します。
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 て、共通言語ランタイムによって管理されるワーカースレッドでコードを実行できます。
このセクションの内容
スレッドの開始
スレッドオブジェクトの取得
フォアグラウンドスレッドとバックグラウンドスレッド
カルチャとスレッド
情報の取得とスレッドの制御
スレッドの開始
スレッドを開始するには、そのクラスコンストラクターでスレッドが実行するメソッドを表すデリゲートを指定します。 次に、メソッドを呼び出して、 Start 実行を開始します。
Threadコンストラクターは、実行するメソッドに引数を渡すことができるかどうかに応じて、次の2つのデリゲート型のどちらかを受け取ることができます。
メソッドに引数がない場合は、デリゲートを ThreadStart コンストラクターに渡します。 署名は次のとおりです。
public delegate void ThreadStart()
Public Delegate Sub ThreadStart()
次の例では、メソッドを実行するスレッドを作成して開始し
ExecuteInForeground
ます。 メソッドは、一部のスレッドプロパティに関する情報を表示した後、0.5 秒間一時停止するループを実行し、経過秒数を表示します。 スレッドが少なくとも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 。 スレッドは、スレッドプロシージャが完了するまで実行を続けます。
スレッドオブジェクトの取得
静的 ( 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 ます。
注意
スレッドプールのスレッドでは、タスクベースの非同期操作が自動的に実行されます。 タスクベースの非同期操作では、クラスとクラスを使用して、 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...
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 カルチャは、リソースファイル内のリソースのカルチャに依存した取得を提供します。
重要
CurrentCultureプロパティと CurrentUICulture プロパティは、現在のスレッド以外のスレッドで使用する場合、確実に動作しません。 .NET Framework では、これらのプロパティの読み取りは信頼性がありますが、現在のスレッド以外のスレッドに対してこれらのプロパティを設定することはできません。 .NET Core では、 InvalidOperationException スレッドが別のスレッドでこれらのプロパティの読み取りまたは書き込みを行おうとすると、がスローされます。 CultureInfo.CurrentCulture CultureInfo.CurrentUICulture 現在のカルチャを取得して設定するには、プロパティとプロパティを使用することをお勧めします。
新しいスレッドがインスタンス化されると、そのカルチャと UI カルチャは、現在のシステムカルチャと ui カルチャによって定義され、新しいスレッドの作成元のスレッドのカルチャおよび UI カルチャによっては定義されません。 たとえば、現在のシステムカルチャが英語 (米国) で、プライマリアプリケーションスレッドの現在のカルチャがフランス語 (フランス) の場合、プライマリスレッドからコンストラクターを呼び出すことによって作成される新しいスレッドのカルチャは、フランス語 (フランス) では Thread(ParameterizedThreadStart) なく英語 (米国) になります。 詳細については、クラスのトピックの「カルチャとスレッド」セクションを参照してください CultureInfo 。
重要
これは、.NET Framework 4.6 以降のバージョンを対象とするアプリに対して非同期操作を実行するスレッドには当てはまりません。この場合、カルチャと ui カルチャは非同期操作のコンテキストに含まれます。既定で実行される非同期操作が実行されるスレッドは、非同期操作の開始元のスレッドのカルチャと ui カルチャを継承します。 詳細については、CultureInfo クラスのトピックの「カルチャとタスク ベースの非同期の操作」セクションをご覧ください。
アプリケーションで実行されているすべてのスレッドが同じカルチャと UI カルチャを共有するようにするには、次のいずれかを実行します。
CultureInfoそのカルチャを表すオブジェクトをデリゲートまたはメソッドに渡すことができ ParameterizedThreadStart ThreadPool.QueueUserWorkItem(WaitCallback, Object) ます。
.NET Framework 4.5 以降のバージョンで実行されているアプリでは、プロパティとプロパティの値を設定することによって、アプリケーションドメインで作成されたすべてのスレッドに割り当てられるカルチャと UI カルチャを定義でき CultureInfo.DefaultThreadCurrentCulture CultureInfo.DefaultThreadCurrentUICulture ます。 これはアプリケーションごとのドメイン設定であることに注意してください。
詳細と例については、クラスのトピックの「カルチャとスレッド」セクションを参照してください CultureInfo 。
情報の取得とスレッドの制御
スレッドに関する情報を提供する多数のプロパティ値を取得できます。 場合によっては、これらのプロパティ値を設定して、スレッドの操作を制御することもできます。 これらのスレッドプロパティは次のとおりです。
名前。 Name は、スレッドを識別するために使用できる1回の書き込みプロパティです。 既定値は
null
です。ハッシュコード。メソッドを呼び出すことによって取得でき GetHashCode ます。 ハッシュコードは、スレッドを一意に識別するために使用できます。スレッドの有効期間にわたって、そのハッシュコードは、値の取得元のアプリケーションドメインに関係なく、他のスレッドの値と競合しません。
スレッド ID。 読み取り専用プロパティの値は、 ManagedThreadId ランタイムによって割り当てられ、プロセス内のスレッドを一意に識別します。
注意
オペレーティング システム ThreadId とマネージド スレッドの間には固定的な関係はありません。これは、アンマネージド ホストがマネージド スレッドとアンマネージド スレッドの間の関係を制御できるためです。 具体的には、高度なホストは CLR ホスティング API を使用して、同じオペレーティングシステムスレッドに対して多数のマネージスレッドをスケジュールしたり、異なるオペレーティングシステムスレッド間でマネージスレッドを移動したりできます。
スレッドの現在の状態。 スレッドは、存在する間、常にプロパティによって定義された1つ以上の状態になり ThreadState ます。
スケジュールの優先度レベル。プロパティによって定義され 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 および |
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) |
スレッドが、 |
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) |
オブジェクトによって公開されたプロパティおよびメソッドへのアクセスを提供します。 |
適用対象
スレッド セーフ
この型はスレッド セーフです。