當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# Thread.CurrentThread用法及代碼示例


Thread類負責在多線程編程中創建和管理線程。它提供了一個稱為CurrentThread的屬性來檢查當前正在運行的線程。換句話說,此屬性的值指示當前正在運行的線程。

用法:public static Thread CurrentThread { get; }

返回值:該屬性返回代表當前運行線程的線程。


以下示例程序旨在說明CurrentThread屬性的用法:

範例1:

// C# program to illustrate the  
// use of CurrentThread property 
using System; 
using System.Threading; 
  
class GFG { 
  
    // Main Method 
    static public void Main() 
    { 
        Thread thr; 
  
        // Get the reference of main Thread 
        // Using CurrentThread property 
        thr = Thread.CurrentThread; 
        thr.Name = "Main thread"; 
        Console.WriteLine("Name of current running "+ 
                            "thread:{0}", thr.Name); 
    } 
}

輸出:

Name of current running thread:Main thread

範例2:

// C# program to illustrate the 
// use of CurrentThread property 
using System; 
using System.Threading; 
  
class GFG { 
  
    // Display the id of each thread 
    // Using CurrentThread and  
    // ManagedThreadId properties 
    public static void Myjob() 
    { 
        Console.WriteLine("Thread Id:{0}",  
           Thread.CurrentThread.ManagedThreadId); 
    } 
  
    // Main method 
    static public void Main() 
    { 
  
        // Creating multiple threads 
        ThreadStart value = new ThreadStart(Myjob); 
        for (int q = 1; q <= 7; ++q)  
        { 
            Thread mythread = new Thread(value); 
            mythread.Start(); 
        } 
    } 
}

輸出:

Thread Id:3
Thread Id:8
Thread Id:9
Thread Id:6
Thread Id:5
Thread Id:7
Thread Id:4

參考:



相關用法


注:本文由純淨天空篩選整理自ankita_saini大神的英文原創作品 Thread.CurrentThread Property in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。