Thread Thread Thread Thread Class

定義

可建立和控制執行緒,設定執行緒的優先權,並取得它的狀態。Creates and controls a thread, sets its priority, and gets its status.

public ref class Thread sealed : System::Runtime::ConstrainedExecution::CriticalFinalizerObject, System::Runtime::InteropServices::_Thread
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Thread : System.Runtime.ConstrainedExecution.CriticalFinalizerObject, System.Runtime.InteropServices._Thread
type Thread = class
    inherit CriticalFinalizerObject
    interface _Thread
Public NotInheritable Class Thread
Inherits CriticalFinalizerObject
Implements _Thread
繼承
屬性
實作

範例

下列範例示範簡單的執行緒處理功能。The following example demonstrates simple threading functionality.

// [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
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

此程式碼會產生類似下列的輸出:This code produces output similar to the following:

[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 會自動建立單一的前景執行緒來執行應用程式程式碼。When a process starts, the common language runtime automatically creates a single foreground thread to execute application code. 這個主要的前景執行緒,以及處理程序可以建立一或多個執行緒來執行此程序相關聯的程式碼的一部分。Along with this main foreground thread, a process can create one or more threads to execute a portion of the program code associated with the process. 這些執行緒可以執行在前景或背景。These threads can execute either in the foreground or in the background. 此外,您可以使用ThreadPoolcommon language runtime 所管理的背景工作執行緒上執行程式碼的類別。In addition, you can use the ThreadPool class to execute code on worker threads that are managed by the common language runtime.

本節內容In this section

正在啟動的執行緒 Starting a thread
擷取執行緒物件 Retrieving Thread objects
前景和背景執行緒 Foreground and background threads
文化特性和執行緒 Culture and threads
取得相關資訊和控制執行緒Getting information about and controlling threads

正在啟動的執行緒Starting a thread

您可以啟動執行緒藉由提供委派,表示執行緒會在其類別建構函式中執行的方法。You start a thread by supplying a delegate that represents the method the thread is to execute in its class constructor. 然後呼叫Start方法,開始執行。You then call the Start method to begin execution.

Thread建構函式可以採用兩個委派類型,取決於是否將引數傳遞至方法,以執行:The Thread constructors can take either of two delegate types, depending on whether you can pass an argument to the method to be executed:

  • 如果方法沒有引數,傳遞ThreadStart委派建構函式。If the method has no arguments, you pass a ThreadStart delegate to the constructor. 其簽章:It has the signature:

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

    下列範例會建立並啟動執行的執行緒ExecuteInForeground方法。The following example creates and starts a thread that executes the ExecuteInForeground method. 方法會顯示某些執行緒屬性的相關資訊,然後執行的迴圈,在其中方法,它可以半秒就會暫停,並顯示經過的秒數。The method displays information about some thread properties, then executes a loop in which it pauses for half a second and displays the elapsed number of seconds. 當執行緒已執行至少 5 秒時,迴圈結束,執行緒會結束執行。When the thread has executed for at least five seconds, the loop ends and the thread terminates execution.

    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()
       {
          DateTime start = DateTime.Now;
          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委派建構函式。If the method has an argument, you pass a ParameterizedThreadStart delegate to the constructor. 其簽章:It has the signature:

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

    然後委派所執行的方法可以轉型 (在 C# 中),或者 (在 Visual Basic) 將參數轉換成適當的類型。The method executed by the delegate can then cast (in C#) or convert (in Visual Basic) the parameter to the appropriate type.

    下列範例等同於前一個位置,不同之處在於它會呼叫Thread(ParameterizedThreadStart)建構函式。The following example is identical to the previous one, except that it calls the Thread(ParameterizedThreadStart) constructor. 這個版本的ExecuteInForeground方法具有單一參數,表示迴圈是要執行的毫秒數的近似數目。This version of the ExecuteInForeground method has a single parameter that represents the approximate number of milliseconds the loop is to execute.

    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;
          }
          DateTime start = DateTime.Now;
          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物件啟動執行緒之後。It is not necessary to retain a reference to a Thread object once you have started the thread. 執行緒會繼續執行直到執行緒程序完成。The thread continues to execute until the thread procedure is complete.

擷取執行緒物件Retrieving Thread objects

您可以使用靜態 (Shared在 Visual Basic 中)CurrentThread屬性來擷取目前執行中執行緒的執行緒正在執行的程式碼的參考。You can use the static (Shared in Visual Basic) CurrentThread property to retrieve a reference to the currently executing thread from the code that the thread is executing. 下列範例會使用CurrentThread屬性來顯示主應用程式執行緒、 另一個前景執行緒,背景執行緒,以及執行緒集區執行緒相關資訊。The following example uses the CurrentThread property to display information about the main application thread, another foreground thread, a background thread, and a thread pool thread.

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

前景和背景執行緒Foreground and background threads

執行個體Thread類別代表前景執行緒或背景執行緒。Instances of the Thread class represent either foreground threads or background threads. 背景執行緒會與相同前景執行緒有一個例外狀況: 在背景執行緒不會保存執行的處理序,如果所有前景執行緒已經都終止。Background threads are identical to foreground threads with one exception: a background thread does not keep a process running if all foreground threads have terminated. 一旦所有前景執行緒已都停止,則執行階段會停止所有背景執行緒,並關閉。Once all foreground threads have been stopped, the runtime stops all background threads and shuts down.

根據預設,下列執行緒會在前景中執行:By default, the following threads execute in the foreground:

  • 主要的應用程式執行緒。The main application thread.

  • 藉由呼叫所建立的所有執行緒Thread類別建構函式。All threads created by calling a Thread class constructor.

根據預設,在背景中執行下列的執行緒:The following threads execute in the background by default:

  • 執行緒集區執行緒,也就是由執行階段所維護的背景工作執行緒集區。Thread pool threads, which are a pool of worker threads maintained by the runtime. 您也可以使用執行緒集區執行緒上設定執行緒集區和排程工作ThreadPool類別。You can configure the thread pool and schedule work on thread pool threads by using the ThreadPool class.

    注意

    在執行緒集區執行緒上自動執行工作為基礎的非同步作業。Task-based asynchronous operations automatically execute on thread pool threads. 使用以工作為基礎的非同步作業TaskTask<TResult>類別來實作工作架構非同步模式Task-based asynchronous operations use the Task and Task<TResult> classes to implement the task-based asynchronous pattern.

  • 從 unmanaged 程式碼來進入 managed 的執行環境的所有執行緒。All threads that enter the managed execution environment from unmanaged code.

您可以變更執行緒在背景中執行,藉由設定IsBackground在任何時間的屬性。You can change a thread to execute in the background by setting the IsBackground property at any time. 背景執行緒可用於任何作業,只要應用程式正在執行,但應該不會防止終止,例如監視檔案系統變更或傳入的通訊端連線應用程式應該繼續。Background threads are useful for any operation that should continue as long as an application is running but should not prevent the application from terminating, such as monitoring file system changes or incoming socket connections.

下列範例說明前景和背景執行緒之間的差異。The following example illustrates the difference between foreground and background threads. 就像中的第一個範例一樣正在啟動的執行緒區段中,不同之處在於它會設定要在背景啟動前先執行的執行緒。It is like the first example in the Starting a thread section, except that it sets the thread to execute in the background before starting it. 如輸出所示,然後才執行五秒將會中斷迴圈。As the output shows, the loop is interrupted before it executes for five seconds.

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()
   {
      DateTime start = DateTime.Now;
      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...

文化特性和執行緒Culture and threads

每個執行緒都所代表文化特性CurrentCulture屬性和 UI 文化特性,以表示CurrentUICulture屬性。Each thread has a culture, represented by the CurrentCulture property, and a UI culture, represented by the CurrentUICulture property. 目前的文化特性支援剖析和格式化、 字串比較和排序,這種區分文化特性的作業,而且也會控制執行緒所使用的行事曆與書寫系統。The current culture supports such culture-sensitive operations as parsing and formatting, string comparison and sorting, and also controls the writing system and calendar used by a thread. 目前的 UI 文化特性提供區分文化特性擷取資源檔中的資源。The current UI culture provides for culture-sensitive retrieval of resources in resource files.

重要

CurrentCultureCurrentUICulture屬性無法可靠地運作,搭配目前的執行緒以外的任何執行緒時。The CurrentCulture and CurrentUICulture properties don't work reliably when used with any thread other than the current thread. 在.NET Framework 中,讀取這些屬性是可靠的但不設定這些屬性目前的執行緒以外的執行緒。In .NET Framework, reading these properties is reliable, although setting these properties for a thread other than the current thread is not. 在.NET Core 上InvalidOperationException如果執行緒嘗試讀取或寫入這些屬性在不同的執行緒上擲回。On .NET Core, an InvalidOperationException is thrown if a thread attempts to read or write these properties on a different thread. 我們建議您改用CultureInfo.CurrentCultureCultureInfo.CurrentUICulture屬性,以擷取和設定目前的文化特性。We recommend that you use the CultureInfo.CurrentCulture and CultureInfo.CurrentUICulture properties to retrieve and set the current culture.

具現化新的執行緒時,其文化特性和 UI 文化特性定義的目前系統文化特性和 UI 文化特性,而不是文化特性和 UI 文化特性,從中建立新的執行緒的執行緒。When a new thread is instantiated, its culture and UI culture are defined by the current system culture and UI culture, and not by the culture and UI culture of the thread from which the new thread is created. 這表示,例如,如果目前的系統文化特性是英文 (美國) 和主要應用程式執行緒的目前文化特性是法文 (法國),藉由呼叫所建立的新執行緒的文化特性Thread(ParameterizedThreadStart)從主執行緒的建構函式英文 (美國) 和法文 (法國)。This means, for example, that if the current system culture is English (United States) and the current culture of the primary application thread is French (France), the culture of a new thread created by calling the Thread(ParameterizedThreadStart) constructor from the primary thread is English (United States), and not French (France). 如需詳細資訊,請參閱的 < 文化特性和執行緒 」 區段CultureInfo類別主題。For more information, see the "Culture and threads" section of the CultureInfo class topic.

重要

這不是執行非同步作業的應用程式為目標的執行緒,則為 true.NET Framework 4.6.NET Framework 4.6和更新版本中的,在此情況下,文化特性和 UI 文化特性是一部分的非同步作業的內容; 的執行緒上非同步作業執行預設繼承的文化特性和 UI 文化特性,從中啟動非同步作業的執行緒。This is not true of threads that execute asynchronous operations for apps that target the .NET Framework 4.6.NET Framework 4.6 and later versions, In this case, the culture and UI culture is part of an asynchronous operations' context; the thread on which an asynchronous operation executes by default inherits the culture and UI culture of the thread from which the asynchronous operation was launched. 如需詳細資訊,請參閱 CultureInfo 類別主題的<文化特性和以工作為基礎的非同步作業>一節。For more information, see the "Culture and task-based asynchronous operations" section of the CultureInfo class topic.

您可以執行下列動作,以確保所有的執行緒執行的應用程式中共用相同的文化特性和 UI 文化特性:You can do either of the following to ensure that all of the threads executing in an application share the same culture and UI culture:

如需詳細資訊和範例,請參閱 「 文化特性和執行緒 > 一節CultureInfo類別主題。For more information and examples, see the "Culture and threads" section of the CultureInfo class topic.

取得相關資訊和控制執行緒Getting information about and controlling threads

您可以擷取提供執行緒的相關資訊的屬性值的數目。You can retrieve a number of property values that provide information about a thread. 在某些情況下,您也可以設定這些屬性值,來控制執行緒的作業。In some cases, you can also set these property values to control the operation of the thread. 這些執行緒屬性包括:These thread properties include:

  • 名稱。A name. Name 已寫入-一次您可用來識別在執行緒中的屬性。Name is a write-once property that you can use to identify a thread. 其預設值是nullIts default value is null.

  • 雜湊程式碼,您可以藉由呼叫擷取GetHashCode方法。A hash code, which you can retrieve by calling the GetHashCode method. 雜湊程式碼可以用來唯一識別執行緒;您的執行緒的存留期內,其雜湊程式碼不將與來自其他執行緒,不論您要從中取得值的應用程式定義域的值相衝突。The hash code can be used to uniquely identify a thread; for the lifetime of your thread, its hash code will not collide with the value from any other thread, regardless of the application domain from which you obtain the value.

  • 執行緒 id。A thread ID. 唯讀值ManagedThreadId屬性由執行階段所指派,以及可唯一識別其處理序內的執行緒。The value of the read-only ManagedThreadId property is assigned by the runtime and uniquely identifies a thread within its process.

    注意

    作業系統的 ThreadId 與 Managed 執行緒之間沒有固定的關係,因為未受管理的主機可控制 Managed 執行緒與 Unmanaged 執行緒之間的關係。An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. 具體來說,精密的主機可以使用CLR 裝載 API排程許多 managed 的執行緒,對相同的作業系統執行緒,或不同的作業系統執行緒之間移動 managed 的執行緒。Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

  • 執行緒的目前狀態。The thread's current state. 其存在期間,執行緒一律是在一或多個定義的狀態ThreadState屬性。For the duration of its existence, a thread is always in one or more of the states defined by the ThreadState property.

  • 排程的優先權層級,可定義ThreadPriority屬性。A scheduling priority level, which is defined by the ThreadPriority property. 雖然您可以設定此值,以要求執行緒的優先權,它不保證適用於作業系統。Although you can set this value to request a thread's priority, it is not guaranteed to be honored by the operating system.

  • 唯讀IsThreadPoolThread屬性,指出執行緒是否在執行緒集區執行緒。The read-only IsThreadPoolThread property, which indicates whether a thread is a thread pool thread.

  • IsBackground 屬性。The IsBackground property. 如需詳細資訊,請參閱 < 前景和背景執行緒一節。For more information, see the Foreground and background threads section.

建構函式

Thread(ParameterizedThreadStart) Thread(ParameterizedThreadStart) Thread(ParameterizedThreadStart) Thread(ParameterizedThreadStart)

初始化 Thread 類別的新執行個體,並指定委派,讓物件可以在執行緒啟動時傳遞到執行緒。Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started.

Thread(ParameterizedThreadStart, Int32) Thread(ParameterizedThreadStart, Int32) Thread(ParameterizedThreadStart, Int32) Thread(ParameterizedThreadStart, Int32)

初始化 Thread 類別的新執行個體,指定委派,讓物件可以在執行緒啟動時傳遞到執行緒,並指定執行緒的堆疊大小上限。Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started and specifying the maximum stack size for the thread.

Thread(ThreadStart) Thread(ThreadStart) Thread(ThreadStart) Thread(ThreadStart)

初始化 Thread 類別的新執行個體。Initializes a new instance of the Thread class.

Thread(ThreadStart, Int32) Thread(ThreadStart, Int32) Thread(ThreadStart, Int32) Thread(ThreadStart, Int32)

初始化 Thread 類別的新執行個體,並指定執行緒的堆疊大小上限。Initializes a new instance of the Thread class, specifying the maximum stack size for the thread.

屬性

ApartmentState ApartmentState ApartmentState ApartmentState

取得或設定這個執行緒的 Apartment 狀態。Gets or sets the apartment state of this thread.

CurrentContext CurrentContext CurrentContext CurrentContext

取得執行緒正在執行的目前內容。Gets the current context in which the thread is executing.

CurrentCulture CurrentCulture CurrentCulture CurrentCulture

取得或設定目前執行緒的文化特性 (Culture)。Gets or sets the culture for the current thread.

CurrentPrincipal CurrentPrincipal CurrentPrincipal CurrentPrincipal

取得或設定執行緒目前的原則 (角色架構安全性之用)。Gets or sets the thread's current principal (for role-based security).

CurrentThread CurrentThread CurrentThread CurrentThread

取得目前執行的執行緒。Gets the currently running thread.

CurrentUICulture CurrentUICulture CurrentUICulture CurrentUICulture

取得或設定資源管理員目前用以在執行階段查詢特定文化特性資源所用的文化特性。Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time.

ExecutionContext ExecutionContext ExecutionContext ExecutionContext

取得 ExecutionContext 物件,包含目前執行緒各種內容的相關資訊。Gets an ExecutionContext object that contains information about the various contexts of the current thread.

IsAlive IsAlive IsAlive IsAlive

取得值,指出目前執行緒的執行狀態。Gets a value indicating the execution status of the current thread.

IsBackground IsBackground IsBackground IsBackground

取得或設定值,指出執行緒是不是背景執行緒。Gets or sets a value indicating whether or not a thread is a background thread.

IsThreadPoolThread IsThreadPoolThread IsThreadPoolThread IsThreadPoolThread

取得值,指出執行緒是否屬於 Managed 執行緒集區。Gets a value indicating whether or not a thread belongs to the managed thread pool.

ManagedThreadId ManagedThreadId ManagedThreadId ManagedThreadId

取得目前 Managed 執行緒的唯一識別項。Gets a unique identifier for the current managed thread.

Name Name Name Name

取得或設定執行緒的名稱。Gets or sets the name of the thread.

Priority Priority Priority Priority

取得或設定值,指出執行緒的排程優先權。Gets or sets a value indicating the scheduling priority of a thread.

ThreadState ThreadState ThreadState ThreadState

取得數值,包含目前執行緒的狀態。Gets a value containing the states of the current thread.

方法

Abort() Abort() Abort() Abort()

於被叫用的所在執行緒中引發 ThreadAbortException,開始處理執行緒的結束作業。Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. 呼叫這個方法通常會結束執行緒。Calling this method usually terminates the thread.

Abort(Object) Abort(Object) Abort(Object) Abort(Object)

於被叫用的所在執行緒中引發 ThreadAbortException,開始結束執行緒的處理作業,同時也提供執行緒結束的相關例外狀況資訊。Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread while also providing exception information about the thread termination. 呼叫這個方法通常會結束執行緒。Calling this method usually terminates the thread.

AllocateDataSlot() AllocateDataSlot() AllocateDataSlot() AllocateDataSlot()

在所有的執行緒上配置未命名的資料位置。Allocates an unnamed data slot on all the threads. 為獲得較佳的效能,請改用以 ThreadStaticAttribute 屬性標示的欄位。For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.

AllocateNamedDataSlot(String) AllocateNamedDataSlot(String) AllocateNamedDataSlot(String) AllocateNamedDataSlot(String)

在所有的執行緒上配置命名的資料位置。Allocates a named data slot on all threads. 為獲得較佳的效能,請改用以 ThreadStaticAttribute 屬性標示的欄位。For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.

BeginCriticalRegion() BeginCriticalRegion() BeginCriticalRegion() BeginCriticalRegion()

通知主機在即將執行的程式碼區域中,執行緒中止或未處理例外狀況的影響,可能會危及應用程式定義域中的其他工作。Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain.

BeginThreadAffinity() BeginThreadAffinity() BeginThreadAffinity() BeginThreadAffinity()

通知主機 Managed 程式碼即將執行指令,而這些指令相依於目前實體作業系統執行緒的識別 (Identity)。Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread.

DisableComObjectEagerCleanup() DisableComObjectEagerCleanup() DisableComObjectEagerCleanup() DisableComObjectEagerCleanup()

關閉目前執行緒之執行階段可呼叫包裝函式 (RCW) 的自動清除功能。Turns off automatic cleanup of runtime callable wrappers (RCW) for the current thread.

EndCriticalRegion() EndCriticalRegion() EndCriticalRegion() EndCriticalRegion()

通知主機在即將執行的程式碼區域中,執行緒中止或未處理例外狀況影響的對象只限於目前的工作。Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception are limited to the current task.

EndThreadAffinity() EndThreadAffinity() EndThreadAffinity() EndThreadAffinity()

通知主機 Managed 程式碼已完成執行指令,而這些指令相依於目前實體作業系統執行緒的識別。Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

確認釋出資源,並在記憶體回收行程回收 Thread 物件時執行其他清除作業。Ensures that resources are freed and other cleanup operations are performed when the garbage collector reclaims the Thread object.

FreeNamedDataSlot(String) FreeNamedDataSlot(String) FreeNamedDataSlot(String) FreeNamedDataSlot(String)

排除處理序中所有執行緒的名稱和位置之間的關聯。Eliminates the association between a name and a slot, for all threads in the process. 為獲得較佳的效能,請改用以 ThreadStaticAttribute 屬性標示的欄位。For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.

GetApartmentState() GetApartmentState() GetApartmentState() GetApartmentState()

傳回表示 Apartment 狀態的 ApartmentState 值。Returns an ApartmentState value indicating the apartment state.

GetCompressedStack() GetCompressedStack() GetCompressedStack() GetCompressedStack()

傳回 CompressedStack 物件,可以用來擷取目前執行緒的堆疊。Returns a CompressedStack object that can be used to capture the stack for the current thread.

GetCurrentProcessorId() GetCurrentProcessorId() GetCurrentProcessorId() GetCurrentProcessorId()
GetData(LocalDataStoreSlot) GetData(LocalDataStoreSlot) GetData(LocalDataStoreSlot) GetData(LocalDataStoreSlot)

從目前執行緒上、目前執行緒之目前定義域中的指定位置擷取數值。Retrieves the value from the specified slot on the current thread, within the current thread's current domain. 為獲得較佳的效能,請改用以 ThreadStaticAttribute 屬性標示的欄位。For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.

GetDomain() GetDomain() GetDomain() GetDomain()

傳回目前執行緒正在其中執行的目前定義域。Returns the current domain in which the current thread is running.

GetDomainID() GetDomainID() GetDomainID() GetDomainID()

傳回唯一的應用程式定義域識別項。Returns a unique application domain identifier.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

傳回目前執行緒的雜湊碼。Returns a hash code for the current thread.

GetNamedDataSlot(String) GetNamedDataSlot(String) GetNamedDataSlot(String) GetNamedDataSlot(String)

尋找具名的資料位置。Looks up a named data slot. 為獲得較佳的效能,請改用以 ThreadStaticAttribute 屬性標示的欄位。For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.

GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
Interrupt() Interrupt() Interrupt() Interrupt()

中斷處於 WaitSleepJoin 執行緒狀態的執行緒。Interrupts a thread that is in the WaitSleepJoin thread state.

Join() Join() Join() Join()

封鎖呼叫執行緒,直到此執行個體所代表的執行緒終止為止,但仍會繼續執行標準的 COM 與 SendMessage 提取作業。Blocks the calling thread until the thread represented by this instance terminates, while continuing to perform standard COM and SendMessage pumping.

Join(Int32) Join(Int32) Join(Int32) Join(Int32)

封鎖呼叫執行緒,直到此執行個體代表的執行緒終止或超過指定的時間為止,但仍繼續執行標準的 COM 與 SendMessage 提取作業。Blocks the calling thread until the thread represented by this instance terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.

Join(TimeSpan) Join(TimeSpan) Join(TimeSpan) Join(TimeSpan)

封鎖呼叫執行緒,直到此執行個體代表的執行緒終止或超過指定的時間為止,但仍繼續執行標準的 COM 與 SendMessage 提取作業。Blocks the calling thread until the thread represented by this instance terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(Inherited from Object)
MemoryBarrier() MemoryBarrier() MemoryBarrier() MemoryBarrier()

同步記憶體存取,如下所示:執行目前執行緒的處理器無法以下列方式重新排序指令:先執行呼叫 MemoryBarrier() 之後的記憶體存取,再執行呼叫 MemoryBarrier() 之前的記憶體存取。Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier() execute after memory accesses that follow the call to MemoryBarrier().

ResetAbort() ResetAbort() ResetAbort() ResetAbort()

取消為目前執行緒要求的 Abort(Object)Cancels an Abort(Object) requested for the current thread.

Resume() Resume() Resume() Resume()

繼續已暫止的執行緒。Resumes a thread that has been suspended.

SetApartmentState(ApartmentState) SetApartmentState(ApartmentState) SetApartmentState(ApartmentState) SetApartmentState(ApartmentState)

在執行緒啟動之前設定其 Apartment 狀態。Sets the apartment state of a thread before it is started.

SetCompressedStack(CompressedStack) SetCompressedStack(CompressedStack) SetCompressedStack(CompressedStack) SetCompressedStack(CompressedStack)

將擷取的 CompressedStack 套用到目前的執行緒。Applies a captured CompressedStack to the current thread.

SetData(LocalDataStoreSlot, Object) SetData(LocalDataStoreSlot, Object) SetData(LocalDataStoreSlot, Object) SetData(LocalDataStoreSlot, Object)

針對那個執行緒目前的定義域,在目前執行之執行緒上的指定位置中設定資料。Sets the data in the specified slot on the currently running thread, for that thread's current domain. 為獲得較佳的效能,請改用以 ThreadStaticAttribute 屬性標示的欄位。For better performance, use fields marked with the ThreadStaticAttribute attribute instead.

Sleep(Int32) Sleep(Int32) Sleep(Int32) Sleep(Int32)

在指定的毫秒數內暫止目前的執行緒。Suspends the current thread for the specified number of milliseconds.

Sleep(TimeSpan) Sleep(TimeSpan) Sleep(TimeSpan) Sleep(TimeSpan)

在指定長度的時間內暫止目前的執行緒。Suspends the current thread for the specified amount of time.

SpinWait(Int32) SpinWait(Int32) SpinWait(Int32) SpinWait(Int32)

造成執行緒等候 iterations 參數定義的次數。Causes a thread to wait the number of times defined by the iterations parameter.

Start() Start() Start() Start()

造成作業系統將目前執行個體的狀態變更為 RunningCauses the operating system to change the state of the current instance to Running.

Start(Object) Start(Object) Start(Object) Start(Object)

使作業系統將目前執行個體的狀態改成 Running,並選擇性地提供物件,在物件中包含執行緒執行之方法所要使用的資料。Causes the operating system to change the state of the current instance to Running, and optionally supplies an object containing data to be used by the method the thread executes.

Suspend() Suspend() Suspend() Suspend()

將執行緒暫止;或者如果執行緒已經暫止,則沒有影響。Either suspends the thread, or if the thread is already suspended, has no effect.

ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)
TrySetApartmentState(ApartmentState) TrySetApartmentState(ApartmentState) TrySetApartmentState(ApartmentState) TrySetApartmentState(ApartmentState)

在執行緒啟動之前設定其 Apartment 狀態。Sets the apartment state of a thread before it is started.

VolatileRead(Byte) VolatileRead(Byte) VolatileRead(Byte) VolatileRead(Byte)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileRead(Double) VolatileRead(Double) VolatileRead(Double) VolatileRead(Double)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileRead(Int16) VolatileRead(Int16) VolatileRead(Int16) VolatileRead(Int16)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileRead(Int32) VolatileRead(Int32) VolatileRead(Int32) VolatileRead(Int32)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileRead(Int64) VolatileRead(Int64) VolatileRead(Int64) VolatileRead(Int64)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileRead(IntPtr) VolatileRead(IntPtr) VolatileRead(IntPtr) VolatileRead(IntPtr)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileRead(Object) VolatileRead(Object) VolatileRead(Object) VolatileRead(Object)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileRead(SByte) VolatileRead(SByte) VolatileRead(SByte) VolatileRead(SByte)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileRead(Single) VolatileRead(Single) VolatileRead(Single) VolatileRead(Single)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileRead(UInt16) VolatileRead(UInt16) VolatileRead(UInt16) VolatileRead(UInt16)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileRead(UInt32) VolatileRead(UInt32) VolatileRead(UInt32) VolatileRead(UInt32)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileRead(UInt64) VolatileRead(UInt64) VolatileRead(UInt64) VolatileRead(UInt64)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileRead(UIntPtr) VolatileRead(UIntPtr) VolatileRead(UIntPtr) VolatileRead(UIntPtr)

讀取欄位值。Reads the value of a field. 值是由電腦中的任意處理器最新寫入的,與處理器的數目或處理器快取的狀態無關。The value is the latest written by any processor in a computer, regardless of the number of processors or the state of processor cache.

VolatileWrite(Byte, Byte) VolatileWrite(Byte, Byte) VolatileWrite(Byte, Byte) VolatileWrite(Byte, Byte)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

VolatileWrite(Double, Double) VolatileWrite(Double, Double) VolatileWrite(Double, Double) VolatileWrite(Double, Double)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

VolatileWrite(Int16, Int16) VolatileWrite(Int16, Int16) VolatileWrite(Int16, Int16) VolatileWrite(Int16, Int16)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

VolatileWrite(Int32, Int32) VolatileWrite(Int32, Int32) VolatileWrite(Int32, Int32) VolatileWrite(Int32, Int32)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

VolatileWrite(Int64, Int64) VolatileWrite(Int64, Int64) VolatileWrite(Int64, Int64) VolatileWrite(Int64, Int64)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

VolatileWrite(IntPtr, IntPtr) VolatileWrite(IntPtr, IntPtr) VolatileWrite(IntPtr, IntPtr) VolatileWrite(IntPtr, IntPtr)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

VolatileWrite(Object, Object) VolatileWrite(Object, Object) VolatileWrite(Object, Object) VolatileWrite(Object, Object)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

VolatileWrite(SByte, SByte) VolatileWrite(SByte, SByte) VolatileWrite(SByte, SByte) VolatileWrite(SByte, SByte)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

VolatileWrite(Single, Single) VolatileWrite(Single, Single) VolatileWrite(Single, Single) VolatileWrite(Single, Single)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

VolatileWrite(UInt16, UInt16) VolatileWrite(UInt16, UInt16) VolatileWrite(UInt16, UInt16) VolatileWrite(UInt16, UInt16)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

VolatileWrite(UInt32, UInt32) VolatileWrite(UInt32, UInt32) VolatileWrite(UInt32, UInt32) VolatileWrite(UInt32, UInt32)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

VolatileWrite(UInt64, UInt64) VolatileWrite(UInt64, UInt64) VolatileWrite(UInt64, UInt64) VolatileWrite(UInt64, UInt64)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

VolatileWrite(UIntPtr, UIntPtr) VolatileWrite(UIntPtr, UIntPtr) VolatileWrite(UIntPtr, UIntPtr) VolatileWrite(UIntPtr, UIntPtr)

立即將值寫入欄位,讓電腦中的所有處理器都可以看到這個值。Writes a value to a field immediately, so that the value is visible to all processors in the computer.

Yield() Yield() Yield() Yield()

造成呼叫執行緒執行目前處理器上已就緒可執行的其他執行緒。Causes the calling thread to yield execution to another thread that is ready to run on the current processor. 作業系統會選擇要執行的執行緒。The operating system selects the thread to yield to.

明確介面實作

_Thread.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Thread.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Thread.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Thread.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。Maps a set of names to a corresponding set of dispatch identifiers.

_Thread.GetTypeInfo(UInt32, UInt32, IntPtr) _Thread.GetTypeInfo(UInt32, UInt32, IntPtr) _Thread.GetTypeInfo(UInt32, UInt32, IntPtr) _Thread.GetTypeInfo(UInt32, UInt32, IntPtr)

擷取物件的類型資訊,可以用來取得介面的類型資訊。Retrieves the type information for an object, which can then be used to get the type information for an interface.

_Thread.GetTypeInfoCount(UInt32) _Thread.GetTypeInfoCount(UInt32) _Thread.GetTypeInfoCount(UInt32) _Thread.GetTypeInfoCount(UInt32)

擷取物件提供的類型資訊介面數目 (0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

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

提供物件所公開的屬性和方法的存取權。Provides access to properties and methods exposed by an object.

適用於

執行緒安全性

此型別具備執行緒安全。This type is thread safe.

另請參閱