There is a code:

Thread newClient = new Thread(StartProcessing); newClient.IsBackground = true; newClient.Start(); 

It executes a function. The stream can be given a name - client number.

How to get the name of the current thread inside the StartProcessing function?

  • Do you need to use string as a stream identifier? just each thread has its own ID (you can get it so Environment.CurrentManagedThreadId). is it not enough? - Stack
  • In the thread name, I will keep the client ID, so it will not work. Thank you - Leonard Bertone
  • in your code before newClient.Start() you need to add newClient.Name = "имя"; - see my answer below. - Stack

3 answers 3

Try using the static class CurrentThread property of Thread - it represents the currently executing thread. For example:

 public static void StartProcessing() { // your code lock(_lockObj) { Console.WriteLine(Thread.CurrentThread.Name); } } 

    GetCurrentThreadId - ID of the current thread.

    For older versions of .NET it is better to use System.Threading.Thread.CurrentThread.ManagedThreadId

      You can use the stream number to get
      Environment.CurrentManagedThreadId or Thread.CurrentThread.ManagedThreadId

      If you need to pass some data to the stream, you can use Thread.GetData and Thread.GetData , as well as the class ThreadLocal .

      If you just need a name, then:

       using System.Threading; var t = new Thread(() => { Console.WriteLine(Thread.CurrentThread.Name); // выводит 123 }); t.Name = "123"; t.Start();