線程被定義爲程序的執行路徑。每個線程定義一個唯一的控制流。如果應用程式涉及複雜且耗時的操作(如資料庫訪問或某些密集的I/O操作),那麼設置不同的執行路徑或線程(每個線程執行特定的作業)通常會很有幫助。
線程是輕量級進程。使用線程的一個常見例子是用現代作業系統實現並發編程。使用線程可以節省CPU周期的浪費,並提高應用程式的效率。
到目前爲止,我們編譯的程序中,一個線程作爲一個進程運行,這個進程是應用程式的運行實例。但是,這樣應用程式可以一次執行一個作業。爲了使它一次執行多個任務,可以將它劃分爲更小的線程。
在.Net中,線程是通過「System.threading」命名空間處理的。通過創建System.Threading.Thread類型的變量,可以創建一個新的開始使用的線程。它允許您在程序中創建和訪問單個線程。
Creating Thread
線程是通過創建線程對象創建的,爲其構造函數提供一個ThreadStart引用。
ThreadStart childthreat = new ThreadStart(childthreadcall);
Thread Life Cycle
線程的生命周期從System.Threading.thread類的對象創建時開始,到線程終止或完成執行時結束。
以下是線程生命周期中的各種狀態:
未啓動狀態:創建線程實例但未調用Start方法時的情況。
就緒狀態:線程準備好執行並等待CPU周期的情況。
不可運行狀態:線程不可運行,當:
- Sleep method has been called
- Wait method has been called
- Blocked by I/O operations
死區狀態:線程已完成執行或已中止的情況。
Thread Priority
Thread類的Priority屬性指定一個線程相對於另一個線程的優先級。.Net運行時選擇優先級最高的就緒線程。
優先事項可分爲:
- Above normal
- Below normal
- Highest
- Lowest
- Normal
創建線程後,將使用thread類的priority屬性設置其優先級。
NewThread.Priority = ThreadPriority.Highest;
Thread Properties & Methods
Thread類具有以下重要屬性:
Property | Description |
---|---|
CurrentContext | Gets the current context in which the thread is executing. |
CurrentCulture | Gets or sets the culture for the current thread. |
CurrentPrinciple | Gets or sets the thread's current principal for role-based security. |
CurrentThread | Gets the currently running thread. |
CurrentUICulture | Gets or sets the current culture used by the Resource Manager to look up culture-specific resources at run time. |
ExecutionContext | Gets an ExecutionContext object that contains information about the various contexts of the current thread. |
IsAlive | Gets a value indicating the execution status of the current thread. |
IsBackground | Gets or sets a value indicating whether or not a thread is a background thread. |
IsThreadPoolThread | Gets a value indicating whether or not a thread belongs to the managed thread pool. |
ManagedThreadId | Gets a unique identifier for the current managed thread. |
Name | Gets or sets the name of the thread. |
Priority | Gets or sets a value indicating the scheduling priority of a thread. |
ThreadState | Gets a value containing the states of the current thread. |
Thread類有以下重要方法:
Methods | Description |
---|---|
Abort | 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. |
AllocateDataSlot | Allocates an unnamed data slot on all the threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. |
AllocateNamedDataSlot | Allocates a named data slot on all threads. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. |
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 endanger other tasks in the application domain. |
BeginThreadAffinity | Notifies a host that managed code is about to execute instructions that depend on the identity of the current physical operating system thread. |
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 | Notifies a host that managed code has finished executing instructions that depend on the identity of the current physical operating system thread. |
FreeNamedDataSlot | Eliminates the association between a name and a slot, for all threads in the process. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. |
GetData | Retrieves the value from the specified slot on the current thread, within the current thread's current domain. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. |
GetDomain | Returns the current domain in which the current thread is running. |
GetDomainID | Returns a unique application domain identifier. |
GetNamedDataSlot | Looks up a named data slot. For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead. |
Interrupt | Interrupts a thread that is in the WaitSleepJoin thread state. |
Join | Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has different overloaded forms. |
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 | Cancels an Abort requested for the current thread. |
SetData | Sets the data in the specified slot on the currently running thread, for that thread's current domain. For better performance, use fields marked with the ThreadStaticAttribute attribute instead. |
Start | Starts a thread. |
Sleep | Makes the thread pause for a period of time. |
SpinWait | Causes a thread to wait the number of times defined by the iterations parameter. |
VolatileRead() | 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. This method has different overloaded forms. |
VolatileWrite() | Writes a value to a field immediately, so that the value is visible to all processors in the computer. This method has different overloaded forms. |
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. |
Example
下面的示例演示了Thread類的用法。頁面有一個標籤控制項,用於顯示來自子線程的消息。使用Response.Write()方法直接顯示來自主程序的消息。因此它們出現在頁面的頂部。
源文件如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="threaddemo._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title> Untitled Page </title> </head> <body> <form id="form1" runat="server"> <div> <h3>Thread Example</h3> </div> <asp:Label ID="lblmessage" runat="server" Text="Label"> </asp:Label> </form> </body> </html>
代碼隱藏文件如下:
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Threading; namespace threaddemo { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ThreadStart childthreat = new ThreadStart(childthreadcall); Response.Write("Child Thread Started <br/>"); Thread child = new Thread(childthreat); child.Start(); Response.Write("Main sleeping for 2 seconds.......<br/>"); Thread.Sleep(2000); Response.Write("<br/>Main aborting child thread<br/>"); child.Abort(); } public void childthreadcall() { try{ lblmessage.Text = "<br />Child thread started <br/>"; lblmessage.Text += "Child Thread: Coiunting to 10"; for( int i =0; i<10; i++) { Thread.Sleep(500); lblmessage.Text += "<br/> in Child thread </br>"; } lblmessage.Text += "<br/> child thread finished"; }catch(ThreadAbortException e){ lblmessage.Text += "<br /> child thread - exception"; }finally{ lblmessage.Text += "<br /> child thread - unable to catch the exception"; } } } }
Observe the following
加載頁時,將使用childthreadcall()方法的引用啓動新線程。主線程活動直接顯示在網頁上。
第二個線程運行並向label控制項發送消息。
主線程休眠2000毫秒,在此期間執行子線程。
子線程一直運行到被主線程中止爲止。它引發ThreadAbortException並被終止。
控制項返回到主線程。
執行時,程序發送以下消息: