📜  C#中的Thread.CurrentThread属性

📅  最后修改于: 2021-05-29 14:43:20             🧑  作者: Mango

Thread类负责在多线程编程中创建和管理线程。它提供了一个称为CurrentThread的属性来检查当前正在运行的线程。换句话说,此属性的值指示当前正在运行的线程。

下面的程序说明了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

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.thread.currentthread?view=netframework-4.7.2