📜  在C#中命名线程并获取当前线程的名称

📅  最后修改于: 2021-05-29 17:09:47             🧑  作者: Mango

线程是进程中的轻量级进程。在C#中,允许用户为线程分配名称,并使用Thread类的Thread.Name属性查找当前工作线程的名称。

句法 :

public string Name { get; set; }

此处,字符串包含线程的名称;如果未分配或设置名称,则该字符串null

重要事项:

  • 默认情况下,Name属性的值为null。
  • 赋予name属性的字符串可以包含任何Unicode字符。
  • Thread类的name属性为一次写入。
  • 如果请求了设置操作,但是Name属性已经设置,则它将给出InvalidOperationException

范例1:

// C# program to illustrate the 
// concept of assigning names 
// to the thread and fetching
// name of the current working thread
using System;
using System.Threading;
  
class Geek {
  
    // Method of Geek class
    public void value()
    {
        // Fetching the name of 
        // the current thread
        // Using Name property
        Thread thr = Thread.CurrentThread;
        Console.WriteLine("The name of the current "+
                           "thread is: " + thr.Name);
    }
}
  
// Driver class
public class GFG {
  
    // Main Method
    static public void Main()
    {
  
        // Creating object of Geek class
        Geek obj = new Geek();
  
        // Creating and initializing threads
        Thread thr1 = new Thread(obj.value);
        Thread thr2 = new Thread(obj.value);
        Thread thr3 = new Thread(obj.value);
        Thread thr4 = new Thread(obj.value);
  
        // Assigning the names of the threads
        // Using Name property
        thr1.Name = "Geeks1";
        thr2.Name = "Geeks2";
        thr3.Name = "Geeks3";
        thr4.Name = "Geeks4";
  
        thr1.Start();
        thr2.Start();
        thr3.Start();
        thr4.Start();
    }
}

输出:

The name of the current thread is: Geeks2
The name of the current thread is: Geeks3
The name of the current thread is: Geeks4
The name of the current thread is: Geeks1

范例2:

// C# program to illustrate the 
// concept of giving a name to thread
using System;
using System.Threading;
  
class Name {
    static void Main()
    {
  
        // Check whether the thread
        // has already been named
        // to avoid InvalidOperationException
        if (Thread.CurrentThread.Name == null) {
  
            Thread.CurrentThread.Name = "MyThread";
            Console.WriteLine("The name of the thread is MyThread");
        }
        else {
            Console.WriteLine("Unable to name the given thread");
        }
    }
}

输出:

The name of the thread is MyThread

参考:

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