使用執行緒和執行緒處理Using threads and threading

使用 .NET,您可以撰寫同時執行多項作業的應用程式。With .NET, you can write applications that perform multiple operations at the same time. 可能妨礙其他作業的作業可以在另外的執行緒上執行,這類處理序稱為「多執行緒」或「無限制執行緒」。Operations with the potential of holding up other operations can execute on separate threads, a process known as multithreading or free threading.

使用多執行緒的應用程式回應使用者輸入會更快,因為當處理器密集工作在另外的執行緒上執行時,使用者介面會保持使用中。Applications that use multithreading are more responsive to user input because the user interface stays active as processor-intensive tasks execute on separate threads. 當您建立可擴充的應用程式時,多執行緒也很有幫助,因為您可以隨著工作負載增加而新增執行緒。Multithreading is also useful when you create scalable applications, because you can add threads as the workload increases.

注意

如果您需要對應用程式執行緒行為有更大的掌控力,您可以自行管理執行緒。If you need more control over the behavior of the application's threads, you can manage the threads yourself. 但是,從 .NET Framework 4 開始,多執行緒的程式設計已透過 System.Threading.Tasks.ParallelSystem.Threading.Tasks.Task 類別、平行 LINQ (PLINQ)System.Collections.Concurrent 命名空間中的新並行集合類別,以及以工作 (而非執行緒) 概念為基礎的新程式設計模型,而做出簡化。However, starting with the .NET Framework 4, multithreaded programming is greatly simplified with the System.Threading.Tasks.Parallel and System.Threading.Tasks.Task classes, Parallel LINQ (PLINQ), new concurrent collection classes in the System.Collections.Concurrent namespace, and a new programming model that is based on the concept of tasks rather than threads. 如需詳細資訊,請參閱平行程式設計工作平行程式庫 (TPL)For more information, see Parallel Programming and Task Parallel Library (TPL).

如何:建立及啟動新的執行緒How to: Create and start a new thread

您可以透過建立 System.Threading.Thread 類別的新執行個體,並將您希望在新的執行緒上執行的方法名稱提供給建構函式,來建立新的執行緒。You create a new thread by creating a new instance of the System.Threading.Thread class and providing the name of the method that you want to execute on a new thread to the constructor. 若要啟動已建立的執行緒,請呼叫 Thread.Start 方法。To start a created thread, call the Thread.Start method. 如需詳細資訊和範例,請參閱建立執行緒並在啟動時傳遞資料一文和 Thread API 參考。For more information and examples, see the Creating threads and passing data at start time article and the Thread API reference.

如何:停止執行緒How to: Stop a thread

若要終止執行緒的執行,請使用 System.Threading.CancellationTokenTo terminate the execution of a thread, use the System.Threading.CancellationToken. 它提供統一的方式來停止執行緒的合作。It provides a unified way to stop threads cooperatively. 如需詳細資訊,請參閱受控執行緒中的取消作業For more information, see Cancellation in managed threads.

有時候,無法以合作方式停止執行緒,因為它會執行協力廠商程式碼,而不是針對合作取消所設計。Sometimes it is not possible to stop a thread cooperatively, because it runs third-party code not designed for cooperative cancellation. 在此情況下,您可能會想要強制終止其執行。In this case, you might want to terminate its execution forcibly. 若要強制終止執行執行緒,您可以在 .NET Framework 中使用 Thread.Abort 方法。To terminate the execution of a thread forcibly, in .NET Framework you can use the Thread.Abort method. 該方法會在叫用該方法的執行緒上引發 ThreadAbortExceptionThat method raises a ThreadAbortException on the thread on which it's invoked. 如需詳細資訊,請參閱終結執行緒For more information, see Destroying threads. .NET Core 不支援 Thread.Abort 方法。The Thread.Abort method is not supported in .NET Core. 如果您需要在 .NET Core 中強制終止協力廠商程式碼的執行,請在個別的進程中執行,並使用 Process.KillIf you need to terminate the execution of third-party code forcibly in .NET Core, run it in the separate process and use Process.Kill.

System.Threading.CancellationToken 在 .NET Framework 4 之前無法使用。The System.Threading.CancellationToken is not available before .NET Framework 4. 若要停止舊版 .NET Framework 版本中的執行緒,您應該使用執行緒同步處理技術來手動執行合作取消。To stop a thread in older .NET Framework versions, you should implement the cooperative cancellation manually using the thread synchronization techniques. 例如,您可以 shouldStop 建立 volatile 布林值欄位,並使用它來要求要停止的執行緒所執行的程式碼。For example, you can create the volatile boolean field shouldStop and use it to request the code executed by the thread to stop. 如需詳細資訊, volatile請參閱C# volatile in Reference 和 System.Threading.VolatileFor more information, see volatile in C# Reference and System.Threading.Volatile.

使用 Thread.Join 方法,讓呼叫執行緒等候停止的執行緒終止。Use the Thread.Join method to make the calling thread wait for the termination of the thread being stopped.

如何:暫停或插斷執行緒How to: Pause or interrupt a thread

您可以使用 Thread.Sleep 方法在指定的時間內暫停目前的執行緒。You use the Thread.Sleep method to pause the current thread for a specified amount of time. 您可以透過呼叫 Thread.Interrupt 方法來插斷封鎖的執行緒。You can interrupt a blocked thread by calling the Thread.Interrupt method. 如需詳細資訊,請參閱暫停及插斷執行緒For more information, see Pausing and interrupting threads.

執行緒屬性Thread properties

下表列出 Thread屬性的一部分:The following table presents some of the Thread properties:

屬性Property 描述Description
IsAlive 若執行緒已啟動且尚未正常終止或中止,則傳回 trueReturns true if a thread has been started and has not yet terminated normally or aborted.
IsBackground 取得或設定布林值,指出執行緒是否為背景執行緒。Gets or sets a Boolean that indicates if a thread is a background thread. 背景執行緒與前景執行緒相似,但背景執行緒不會防止處理序停止。Background threads are like foreground threads, but a background thread doesn't prevent a process from stopping. 一旦屬於處理程序的所有前景執行緒停止,通用語言執行平台會呼叫背景執行緒上仍在執行的 Abort 方法來結束處理程序。Once all foreground threads that belong to a process have stopped, the common language runtime ends the process by calling the Abort method on background threads that are still alive. 如需詳細資訊,請參閱前景與背景執行緒For more information, see Foreground and Background Threads.
Name 取得或設定執行緒名稱。Gets or sets the name of a thread. 最常用於在偵錯時探索個別執行緒。Most frequently used to discover individual threads when you debug.
Priority 取得或設定作業系統使用的 ThreadPriority 值,以設定執行緒排程的優先權。Gets or sets a ThreadPriority value that is used by the operating system to prioritize thread scheduling. 如需詳細資訊,請參閱排程執行緒ThreadPriority 參考。For more information, see Scheduling threads and the ThreadPriority reference.
ThreadState 取得包含執行緒目前狀態的 ThreadState 值。Gets a ThreadState value containing the current states of a thread.

請參閱See also