按一下以給予評分及指教
MSDN
MSDN Library
.NET 開發
.NET Framework
Thread 類別

  開啟低頻寬檢視
本頁僅適用於
Microsoft Visual Studio 2008/.NET Framework 3.5

其他版本也適用於下列軟體:
.NET Framework 類別庫
Thread 類別

更新:2007 年 11 月

可建立和控制執行緒,設定執行緒的優先權,並取得它的狀態。

命名空間:  System.Threading
組件:  mscorlib (在 mscorlib.dll 中)

Visual Basic (宣告)
<ComVisibleAttribute(True)> _
<ClassInterfaceAttribute(ClassInterfaceType.None)> _
Public NotInheritable Class Thread _
    Inherits CriticalFinalizerObject _
    Implements _Thread
Visual Basic (使用方式)
Dim instance As Thread
C#
[ComVisibleAttribute(true)]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
public sealed class Thread : CriticalFinalizerObject, 
    _Thread
Visual C++
[ComVisibleAttribute(true)]
[ClassInterfaceAttribute(ClassInterfaceType::None)]
public ref class Thread sealed : public CriticalFinalizerObject, 
    _Thread
J#
/** @attribute ComVisibleAttribute(true) */
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.None) */
public final class Thread extends CriticalFinalizerObject implements _Thread
JScript
public final class Thread extends CriticalFinalizerObject implements _Thread

處理序可建立一個以上的執行緒,來執行與處理序相關的一部分程式碼。請使用 ThreadStart 委派 (Delegate) 或 ParameterizedThreadStart 委派來指定執行緒所執行的程式碼。ParameterizedThreadStart 委派可以讓您將資料傳遞到執行緒程序。

執行緒只要是存在的期間,總是在 ThreadState 定義的一種以上的狀態中。排程優先權層級以 ThreadPriority 所定義的為例,雖然可以向它要求執行緒,但不保證作業系統一定會承認。

GetHashCode 提供 Managed 執行緒識別。執行緒在存留期不會與任何其他執行緒值衝突 (不考慮從哪個應用程式定義域取得此值)。

注意事項:

作業系統 ThreadId 和 Managed 執行緒沒有固定關聯性,因為 Unmanaged 主機可以控制 Managed 和 Unmanaged 執行緒之間的關聯性。尤其成熟的主機可以使用 CLR Hosting API 為相同的作業系統執行緒排定許多 Managed 執行緒,或是在不同的作業系統執行緒之間移動 Managed 執行緒。

啟動執行緒之後,就不需要保留 Thread 物件的參考。執行緒會繼續執行,直到執行緒程序完成為止。

以下程式碼範例示範簡單的執行緒功能。

Visual Basic
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

C#
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();
    }
}

Visual C++
// [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;
}


J#
import System.*;
import 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() throws InterruptedException
    {
        for (int i = 0; i < 10; i++) {
            Console.WriteLine("ThreadProc: {0}", System.Convert.ToString(i));
            // Yield the rest of the time slice.
            Thread.sleep(0);
        }
    } //ThreadProc

    public static void main(String[] args) throws InterruptedException
    {
        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.  J# simplifies the creation of this delegate.
        System.Threading.Thread t =
            new System.Threading.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();
    } //main
} //ThreadExample

這個程式碼會產生類似下列的輸出:

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

此型別具備執行緒安全。

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360

.NET Framework 和 .NET Compact Framework 並不支援各種平台的所有版本。如需支援平台版本的相關資訊,請參閱 .NET Framework 系統需求

.NET Framework

支援版本:3.5、3.0、2.0、1.1、1.0

.NET Compact Framework

支援版本:3.5、2.0、1.0

XNA Framework

支援版本:2.0、1.0
社群內容   什麼是社群內容?
新增內容 RSS  註解
Processing
© 2009 Microsoft Corporation. 著作權所有,並保留一切權利。 使用規定  |  商標  |  隱私權聲明
Page view tracker