如何从 C# 中的线程获取线程 ID?
线程被定义为程序的执行路径。每个线程定义一个独特的控制流。如果你的应用程序涉及复杂且耗时的操作,那么设置不同的执行路径或线程通常很有用,每个线程执行特定任务。
线程是轻量级进程。线程的一个常见使用示例是现代操作系统实现并发编程。使用线程可以节省 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP