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.
備註
當處理常式啟動時,common language runtime 會自動建立單一的前景執行緒來執行應用程式程式碼。 除了這個主要的前景執行緒,進程還可以建立一或多個執行緒來執行與進程相關聯的程式碼部分。 這些執行緒可以在前景或背景執行。 此外,您可以使用類別, ThreadPool 在 common language runtime 所管理的背景工作執行緒上執行程式碼。
本節內容
啟動執行緒
正在抓取執行緒物件
前景和背景執行緒
文化特性和執行緒
取得和控制執行緒的相關資訊
啟動執行緒
您可以藉由提供委派來啟動執行緒,以表示執行緒在其類別的函式中執行的方法。 然後,您可以呼叫 Start 方法來開始執行。
Thread根據您是否可以將引數傳遞給要執行的方法,這些函數可採用兩種委派類型:
如果方法沒有引數,您可以將委派傳遞至函式 ThreadStart 。 它有簽章:
public delegate void ThreadStart()
Public Delegate Sub ThreadStart()
下列範例會建立並啟動執行方法的執行緒
ExecuteInForeground
。 方法會顯示某些執行緒屬性的相關資訊,然後執行迴圈,其中會暫停半秒,並顯示經過的秒數。 當執行緒至少執行五秒時,迴圈就會結束,且執行緒會終止執行。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
方法具有單一參數,表示迴圈執行的大約毫秒數。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 代表前景執行緒或背景執行緒。 背景執行緒與前景執行緒完全相同,但有一個例外狀況:如果所有前景執行緒都已終止,則背景執行緒不會讓進程繼續執行。 一旦停止所有前景執行緒之後,執行時間就會停止所有背景執行緒並關閉。
根據預設,下列執行緒會在前景中執行:
主要應用程式執行緒。
藉由呼叫類別的函式來建立的所有線程 Thread 。
下列執行緒預設會在背景中執行:
執行緒集區執行緒,這是由執行時間維護的背景工作執行緒集區。 您可以使用類別,線上程集區執行緒上設定執行緒集區和排程工作 ThreadPool 。
注意
以工作為基礎的非同步作業會自動線上程集區執行緒上執行。 以工作為基礎的非同步作業會使用 Task 和 Task<TResult> 類別來執行以工作為 基礎的非同步模式。
從非受控碼進入 managed 執行環境的所有線程。
您可以隨時設定屬性,以變更在背景中執行的執行緒 IsBackground 。 背景執行緒適用于任何應該繼續執行的作業,只要應用程式正在執行,但不應該阻止應用程式終止,例如監視檔案系統變更或傳入通訊端連線。
下列範例說明前景和背景執行緒之間的差異。 它就像是 啟動執行緒 一節中的第一個範例,不同之處在于它會先設定執行緒在背景中執行,然後再啟動它。 如輸出所示,迴圈會在執行五秒之前中斷。
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 這是一次可供您用來識別執行緒的寫入屬性。 其預設值為
null
。您可以藉由呼叫方法來取得的雜湊碼 GetHashCode 。 雜湊碼可以用來唯一識別執行緒;線上程的存留期內,其雜湊程式碼不會與任何其他執行緒的值相衝突,不論您取得值的應用程式網域為何。
執行緒識別碼。 唯讀屬性的值 ManagedThreadId 是由執行時間所指派,並且可唯一識別其進程內的執行緒。
注意
作業系統的 ThreadId 與 Managed 執行緒之間沒有固定的關係,因為未受管理的主機可控制 Managed 執行緒與 Unmanaged 執行緒之間的關係。 具體來說,精密的主機可以使用 CLR 裝載 API ,針對相同的作業系統執行緒排程許多 managed 執行緒,或在不同的作業系統執行緒之間移動受控執行緒。
執行緒的目前狀態。 在其存在期間,執行緒一律會處於屬性所定義的一或多個狀態 ThreadState 。
排程優先權層級,由 ThreadPriority 屬性定義。 雖然您可以將此值設定為要求執行緒的優先權,但作業系統不保證會接受它。
唯讀 IsThreadPoolThread 屬性,指出執行緒是否為執行緒集區執行緒。
IsBackground 屬性。 如需詳細資訊,請參閱 前景和背景執行緒 一節。
建構函式
Thread(ParameterizedThreadStart) |
初始化 Thread 類別的新執行個體,並指定委派,讓物件可以在執行緒啟動時傳遞到執行緒。 |
Thread(ParameterizedThreadStart, Int32) |
初始化 Thread 類別的新執行個體,指定委派,讓物件可以在執行緒啟動時傳遞到執行緒,並指定執行緒的堆疊大小上限。 |
Thread(ThreadStart) |
初始化 Thread 類別的新執行個體。 |
Thread(ThreadStart, Int32) |
初始化 Thread 類別的新執行個體,並指定執行緒的堆疊大小上限。 |
屬性
ApartmentState |
已過時。
已過時。
已過時。
取得或設定這個執行緒的 Apartment 狀態。 |
CurrentContext |
取得執行緒正在執行的目前內容。 |
CurrentCulture |
取得或設定目前執行緒的文化特性 (Culture)。 |
CurrentPrincipal |
取得或設定執行緒目前的原則 (角色架構安全性之用)。 |
CurrentThread |
取得目前執行的執行緒。 |
CurrentUICulture |
取得或設定資源管理員目前用以在執行階段查詢特定文化特性資源所用的文化特性。 |
ExecutionContext |
取得 ExecutionContext 物件,包含目前執行緒各種內容的相關資訊。 |
IsAlive |
取得值,指出目前執行緒的執行狀態。 |
IsBackground |
取得或設定值,指出執行緒是不是背景執行緒。 |
IsThreadPoolThread |
取得值,指出執行緒是否屬於 Managed 執行緒集區。 |
ManagedThreadId |
取得目前 Managed 執行緒的唯一識別項。 |
Name |
取得或設定執行緒的名稱。 |
Priority |
取得或設定值,指出執行緒的排程優先權。 |
ThreadState |
取得數值,包含目前執行緒的狀態。 |
方法
Abort() |
已過時。
於被叫用的所在執行緒中引發 ThreadAbortException,開始處理執行緒的結束作業。 呼叫這個方法通常會結束執行緒。 |
Abort(Object) |
已過時。
於被叫用的所在執行緒中引發 ThreadAbortException,開始結束執行緒的處理作業,同時也提供執行緒結束的相關例外狀況資訊。 呼叫這個方法通常會結束執行緒。 |
AllocateDataSlot() |
在所有的執行緒上配置未命名的資料位置。 為獲得較佳的效能,請改用以 ThreadStaticAttribute 屬性標示的欄位。 |
AllocateNamedDataSlot(String) |
在所有的執行緒上配置命名的資料位置。 為獲得較佳的效能,請改用以 ThreadStaticAttribute 屬性標示的欄位。 |
BeginCriticalRegion() |
通知主機在即將執行的程式碼區域中,執行緒中止或未處理例外狀況的影響,可能會危及應用程式定義域中的其他工作。 |
BeginThreadAffinity() |
通知主機 Managed 程式碼即將執行指令,而這些指令相依於目前實體作業系統執行緒的識別 (Identity)。 |
DisableComObjectEagerCleanup() |
關閉目前執行緒之執行階段可呼叫包裝函式 (RCW) 的自動清除功能。 |
EndCriticalRegion() |
通知主機在即將執行的程式碼區域中,執行緒中止或未處理例外狀況影響的對象只限於目前的工作。 |
EndThreadAffinity() |
通知主機 Managed 程式碼已完成執行指令,而這些指令相依於目前實體作業系統執行緒的識別。 |
Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
Finalize() |
確認釋出資源,並在記憶體回收行程回收 Thread 物件時執行其他清除作業。 |
FreeNamedDataSlot(String) |
排除處理序中所有執行緒的名稱和位置之間的關聯。 為獲得較佳的效能,請改用以 ThreadStaticAttribute 屬性標示的欄位。 |
GetApartmentState() |
傳回表示 Apartment 狀態的 ApartmentState 值。 |
GetCompressedStack() |
已過時。
已過時。
傳回 CompressedStack 物件,可以用來擷取目前執行緒的堆疊。 |
GetCurrentProcessorId() |
取得用來指出目前執行緒正在哪個處理器上執行的識別碼。 |
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) |
在執行緒啟動之前設定其 Apartment 狀態。 |
SetCompressedStack(CompressedStack) |
已過時。
已過時。
將擷取的 CompressedStack 套用到目前的執行緒。 |
SetData(LocalDataStoreSlot, Object) |
針對那個執行緒目前的定義域,在目前執行之執行緒上的指定位置中設定資料。 為獲得較佳的效能,請改用以 ThreadStaticAttribute 屬性標示的欄位。 |
Sleep(Int32) |
在指定的毫秒數內暫止目前的執行緒。 |
Sleep(TimeSpan) |
在指定長度的時間內暫止目前的執行緒。 |
SpinWait(Int32) |
造成執行緒等候 |
Start() |
造成作業系統將目前執行個體的狀態變更為 Running。 |
Start(Object) |
使作業系統將目前執行個體的狀態改成 Running,並選擇性地提供物件,在物件中包含執行緒執行之方法所要使用的資料。 |
Suspend() |
已過時。
已過時。
已過時。
將執行緒暫止;或者如果執行緒已經暫止,則沒有影響。 |
ToString() |
傳回代表目前物件的字串。 (繼承來源 Object) |
TrySetApartmentState(ApartmentState) |
在執行緒啟動之前設定其 Apartment 狀態。 |
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) |
將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。 |
_Thread.GetTypeInfo(UInt32, UInt32, IntPtr) |
擷取物件的類型資訊,可以用來取得介面的類型資訊。 |
_Thread.GetTypeInfoCount(UInt32) |
擷取物件提供的類型資訊介面數目 (0 或 1)。 |
_Thread.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
提供物件所公開的屬性和方法的存取權。 |
適用於
執行緒安全性
此型別具備執行緒安全。