C# | Obtener el identificador único para el subproceso administrado actual

Una clase Thread es responsable de crear y administrar un hilo en la programación multihilo. Proporciona una propiedad conocida como ManagedThreadId para verificar el identificador único del subproceso administrado actual. O en otras palabras, el valor de la propiedad ManagedThreadId de un subproceso define de forma única ese subproceso dentro de su proceso. El valor de la propiedad ManagedThreadId no varía según el tiempo.

Sintaxis:

public int ManagedThreadId { get; }

Valor de retorno: esta propiedad devuelve un valor que indica un identificador único para este subproceso administrado. El tipo de valor devuelto de esta propiedad es System.Int32 .

Ejemplo 1:

// C# program to illustrate the 
// use of ManagedThreadId property
using System;
using System.Threading;
  
public class GFG {
  
    // Main Method
    static public void Main()
    {
        Thread T;
  
        // Get the reference of main Thread
        // Using CurrentThread property
        T = Thread.CurrentThread;
  
        // Display the unique id of the main 
        // thread Using ManagedThreadId property
        Console.WriteLine("The unique id of the main "+
                 "thread is: {0} ", T.ManagedThreadId);
    }
}

Producción:

The unique id of the main thread is: 1 

Ejemplo 2:

// C# program to illustrate the 
// use of ManagedThreadId property
using System;
using System.Threading;
  
public class GFG {
  
    // Main method
    public static void Main()
    {
        // Creating and initializing threads
        Thread thr1 = new Thread(new ThreadStart(job));
        Thread thr2 = new Thread(new ThreadStart(job));
        Thread thr3 = new Thread(new ThreadStart(job));
  
        Console.WriteLine("ManagedThreadId of thread 1 "+
                        "is: {0}", thr1.ManagedThreadId);
  
        Console.WriteLine("ManagedThreadId of thread 2 "+
                        "is: {0}", thr2.ManagedThreadId);
  
        Console.WriteLine("ManagedThreadId of thread 3 "+
                        "is: {0}", thr3.ManagedThreadId);
  
        // Running state
        thr1.Start();
        thr2.Start();
        thr3.Start();
    }
  
    // Static method
    public static void job()
    {
        Thread.Sleep(2000);
    }
}

Producción:

ManagedThreadId of thread 1 is: 3
ManagedThreadId of thread 2 is: 4
ManagedThreadId of thread 3 is: 5

Referencia:

Publicación traducida automáticamente

Artículo escrito por ankita_saini y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *