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.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. 此外,您可以使用ThreadPool類別,在 common 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
正在抓取 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. 當執行緒至少執行五秒時,迴圈就會結束,執行緒就會終止執行。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.

正在抓取 Thread 物件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. 以工作Task為基礎的非同步作業會Task<TResult>使用和類別來執行以工作為基礎的非同步模式Task-based asynchronous operations use the Task and Task<TResult> classes to implement the task-based asynchronous pattern.

  • 所有從非受控碼進入 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.

重要

與目前CurrentUICulture執行緒以外的任何執行緒搭配使用時,和屬性無法可靠地執行。CurrentCultureThe 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.CurrentCulture建議您使用和CultureInfo.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.

重要

對於以和更新版本為目標的.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.

  • 執行緒識別碼。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 ,針對相同的作業系統執行緒排程許多受控執行緒,或在不同的作業系統執行緒之間移動受控執行緒。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 的淺層複本 (Shallow Copy)。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.

另請參閱