Ler en inglés

Compartir por


Thread.Join Método

Definición

Bloquea el subproceso de llamada hasta que finaliza el subproceso representado por esta instancia.

Sobrecargas

Join()

Bloquea el subproceso de llamada hasta que el subproceso representado por esta instancia finaliza, pero continúa bombeando SendMessage y COM estándar.

Join(Int32)

Bloquea el subproceso de llamada hasta que el subproceso representado por esta instancia finaliza o transcurre el tiempo especificado, pero continúa bombeando SendMessage y COM estándar.

Join(TimeSpan)

Bloquea el subproceso de llamada hasta que el subproceso representado por esta instancia finaliza o transcurre el tiempo especificado, pero continúa bombeando SendMessage y COM estándar.

Join()

Source:
Thread.cs
Source:
Thread.cs
Source:
Thread.cs

Bloquea el subproceso de llamada hasta que el subproceso representado por esta instancia finaliza, pero continúa bombeando SendMessage y COM estándar.

C#
public void Join();

Excepciones

El autor de la llamada ha intentado combinar un subproceso que se encuentra en el estado Unstarted.

El subproceso se interrumpe mientras espera.

Comentarios

Join es un método de sincronización que bloquea el subproceso que realiza la llamada (es decir, el subproceso que llama al método ) hasta que se haya completado el subproceso cuyo Join método se llama. Use este método para asegurarse de que se ha terminado un subproceso. El autor de la llamada se bloqueará indefinidamente si el subproceso no finaliza. En el ejemplo siguiente, el Thread1 subproceso llama al Join() método de Thread2, lo que hace Thread1 que se bloquee hasta Thread2 que se haya completado.

C#
using System;
using System.Threading;

public class Example
{
   static Thread thread1, thread2;
   
   public static void Main()
   {
      thread1 = new Thread(ThreadProc);
      thread1.Name = "Thread1";
      thread1.Start();
      
      thread2 = new Thread(ThreadProc);
      thread2.Name = "Thread2";
      thread2.Start();   
   }

   private static void ThreadProc()
   {
      Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name);
      if (Thread.CurrentThread.Name == "Thread1" && 
          thread2.ThreadState != ThreadState.Unstarted)
         thread2.Join();
      
      Thread.Sleep(4000);
      Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name);
      Console.WriteLine("Thread1: {0}", thread1.ThreadState);
      Console.WriteLine("Thread2: {0}\n", thread2.ThreadState);
   }
}
// The example displays output like the following:
//       Current thread: Thread1
//       
//       Current thread: Thread2
//       
//       Current thread: Thread2
//       Thread1: WaitSleepJoin
//       Thread2: Running
//       
//       
//       Current thread: Thread1
//       Thread1: Running
//       Thread2: Stopped

Si el subproceso ya ha finalizado cuando Join se llama a , el método devuelve inmediatamente.

Aviso

Nunca debe llamar al Join método del Thread objeto que representa el subproceso actual del subproceso actual. Esto hace que la aplicación deje de responder porque el subproceso actual espera indefinidamente,

Este método cambia el estado del subproceso que realiza la llamada para incluir ThreadState.WaitSleepJoin. No se puede invocar en un subproceso Join que esté en el ThreadState.Unstarted estado .

Consulte también

Se aplica a

.NET 10 e outras versións
Produto Versións
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Join(Int32)

Source:
Thread.cs
Source:
Thread.cs
Source:
Thread.cs

Bloquea el subproceso de llamada hasta que el subproceso representado por esta instancia finaliza o transcurre el tiempo especificado, pero continúa bombeando SendMessage y COM estándar.

C#
public bool Join(int millisecondsTimeout);

Parámetros

millisecondsTimeout
Int32

Número de milisegundos durante los que se va a esperar a que el subproceso finalice.

Devoluciones

true si el subproceso ha terminado; false si el subproceso no ha terminado una vez transcurrido el período de tiempo especificado por el parámetro millisecondsTimeout.

Excepciones

El valor de millisecondsTimeout es negativo y no es igual a Infinite en milisegundos.

No se ha iniciado el subproceso.

millisecondsTimeout es menor que -1 (Timeout.Infinite).

El subproceso se ha interrumpido mientras se esperaba.

Comentarios

Join(Int32) es un método de sincronización que bloquea el subproceso que realiza la llamada (es decir, el subproceso que llama al método) hasta que el subproceso cuyo Join método se llama haya completado o haya transcurrido el intervalo de tiempo de espera. En el ejemplo siguiente, el Thread1 subproceso llama al Join() método de Thread2, lo que hace Thread1 que se bloquee hasta Thread2 que haya finalizado o 2 segundos haya transcurrido.

C#
using System;
using System.Threading;

public class Example
{
   static Thread thread1, thread2;
   
   public static void Main()
   {
      thread1 = new Thread(ThreadProc);
      thread1.Name = "Thread1";
      thread1.Start();
      
      thread2 = new Thread(ThreadProc);
      thread2.Name = "Thread2";
      thread2.Start();   
   }

   private static void ThreadProc()
   {
      Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name);
      if (Thread.CurrentThread.Name == "Thread1" && 
          thread2.ThreadState != ThreadState.Unstarted)
         if (thread2.Join(2000))
            Console.WriteLine("Thread2 has termminated.");
         else
            Console.WriteLine("The timeout has elapsed and Thread1 will resume.");   
      
      Thread.Sleep(4000);
      Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name);
      Console.WriteLine("Thread1: {0}", thread1.ThreadState);
      Console.WriteLine("Thread2: {0}\n", thread2.ThreadState);
   }
}
// The example displays the following output:
//       Current thread: Thread1
//       
//       Current thread: Thread2
//       The timeout has elapsed and Thread1 will resume.
//       
//       Current thread: Thread2
//       Thread1: WaitSleepJoin
//       Thread2: Running
//       
//       
//       Current thread: Thread1
//       Thread1: Running
//       Thread2: Stopped

Si Timeout.Infinite se especifica para el millisecondsTimeout parámetro , este método se comporta de forma idéntica a la sobrecarga del Join() método, excepto el valor devuelto.

Si el subproceso ya ha finalizado cuando Join se llama a , el método devuelve inmediatamente.

Este método cambia el estado del subproceso que realiza la llamada para incluir ThreadState.WaitSleepJoin. No se puede invocar en un subproceso Join que esté en el ThreadState.Unstarted estado .

Consulte también

Se aplica a

.NET 10 e outras versións
Produto Versións
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

Join(TimeSpan)

Source:
Thread.cs
Source:
Thread.cs
Source:
Thread.cs

Bloquea el subproceso de llamada hasta que el subproceso representado por esta instancia finaliza o transcurre el tiempo especificado, pero continúa bombeando SendMessage y COM estándar.

C#
public bool Join(TimeSpan timeout);

Parámetros

timeout
TimeSpan

Un TimeSpan establecido en el período de tiempo durante el que se esperará a que espere el subproceso.

Devoluciones

true si el subproceso ha terminado; false si el subproceso no ha terminado una vez transcurrido el período de tiempo especificado por el parámetro timeout.

Excepciones

El valor de timeout es negativo y no es igual a Infinite en milisegundos, o es mayor que Int32.MaxValue milisegundos.

El autor de la llamada ha intentado combinar un subproceso que se encuentra en el estado Unstarted.

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar un TimeSpan valor con el Join método .

C#
using System;
using System.Threading;

class Test
{
    static TimeSpan waitTime = new TimeSpan(0, 0, 1);

    public static void Main() 
    {
        Thread newThread = new Thread(Work);
        newThread.Start();

        if(newThread.Join(waitTime + waitTime)) {
            Console.WriteLine("New thread terminated.");
        }
        else {
            Console.WriteLine("Join timed out.");
        }
    }

    static void Work()
    {
        Thread.Sleep(waitTime);
    }
}
// The example displays the following output:
//        New thread terminated.

Comentarios

Join(TimeSpan) es un método de sincronización que bloquea el subproceso que realiza la llamada (es decir, el subproceso que llama al método) hasta que el subproceso cuyo Join método se llama haya completado o haya transcurrido el intervalo de tiempo de espera. En el ejemplo siguiente, el Thread1 subproceso llama al Join() método de Thread2, lo que hace Thread1 que se bloquee hasta Thread2 que haya finalizado o 2 segundos haya transcurrido.

C#
using System;
using System.Threading;

public class Example
{
   static Thread thread1, thread2;
   
   public static void Main()
   {
      thread1 = new Thread(ThreadProc);
      thread1.Name = "Thread1";
      thread1.Start();
      
      thread2 = new Thread(ThreadProc);
      thread2.Name = "Thread2";
      thread2.Start();   
   }

   private static void ThreadProc()
   {
      Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name);
      if (Thread.CurrentThread.Name == "Thread1" && 
          thread2.ThreadState != ThreadState.Unstarted)
         if (thread2.Join(TimeSpan.FromSeconds(2)))
            Console.WriteLine("Thread2 has termminated.");
         else
            Console.WriteLine("The timeout has elapsed and Thread1 will resume.");   
      
      Thread.Sleep(4000);
      Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name);
      Console.WriteLine("Thread1: {0}", thread1.ThreadState);
      Console.WriteLine("Thread2: {0}\n", thread2.ThreadState);
   }
}
// The example displays the following output:
//       Current thread: Thread1
//       
//       Current thread: Thread2
//       The timeout has elapsed and Thread1 will resume.
//       
//       Current thread: Thread2
//       Thread1: WaitSleepJoin
//       Thread2: Running
//       
//       
//       Current thread: Thread1
//       Thread1: Running
//       Thread2: Stopped

Si Timeout.Infinite se especifica para timeout, este método se comporta de forma idéntica a la sobrecarga del Join() método, excepto el valor devuelto.

Si el subproceso ya ha finalizado cuando Join se llama a , el método devuelve inmediatamente.

Este método cambia el estado del subproceso actual para incluir WaitSleepJoin. No se puede invocar en un subproceso Join que esté en el ThreadState.Unstarted estado .

Consulte también

Se aplica a

.NET 10 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1