如何在 C# 中从线程获取线程 ID?
csharpserver side programmingprogramming
线程定义为程序的执行路径。每个线程都定义一个唯一的控制流。如果您的应用程序涉及复杂且耗时的操作,那么设置不同的执行路径或线程通常会很有帮助,每个线程执行特定的工作。
线程是轻量级进程。使用线程的一个常见示例是现代操作系统实现并发编程。使用线程可以节省 CPU 周期的浪费并提高应用程序的效率。
在 C# 中,System.Threading.Thread 类用于处理线程。它允许在多线程应用程序中创建和访问单个线程。进程中要执行的第一个线程称为主线程。
当 C# 程序开始执行时,会自动创建主线程。使用 Thread 类创建的线程称为主线程的子线程。您可以使用 Thread 类的 CurrentThread 属性访问线程。
示例
class Program{ public static void Main(){ Thread thr; thr = Thread.CurrentThread; thr.Name = "Main thread"; Console.WriteLine("Name of current running " + "thread: {0}", Thread.CurrentThread.Name); Console.WriteLine("Id of current running " + "thread: {0}", Thread.CurrentThread.ManagedThreadId); Console.ReadLine(); } }
输出
Name of current running thread: Main thread Id of current running thread: 1