Compartir por


Thread.IsBackground Propiedad

Definición

Obtiene o establece un valor que indica si un subproceso es un subproceso en segundo plano o no.

public:
 property bool IsBackground { bool get(); void set(bool value); };
public bool IsBackground { get; set; }
member this.IsBackground : bool with get, set
Public Property IsBackground As Boolean

Valor de propiedad

true si este subproceso es o se va a convertir en un subproceso en segundo plano; de lo contrario, false.

Excepciones

El subproceso está muerto.

Ejemplos

En el ejemplo siguiente se contrasta el comportamiento de los subprocesos en primer plano y en segundo plano. Crea un subproceso en primer plano y un subproceso en segundo plano. El subproceso en primer plano mantiene el proceso en ejecución hasta que finaliza su for bucle y finaliza. Sin embargo, como se muestra en la salida del ejemplo, porque el subproceso en primer plano ha finalizado la ejecución, el proceso finaliza antes de que el subproceso en segundo plano haya completado la ejecución.

using System;
using System.Threading;

class Example
{
    static void Main()
    {
        BackgroundTest shortTest = new BackgroundTest(10);
        Thread foregroundThread = 
            new Thread(new ThreadStart(shortTest.RunLoop));

        BackgroundTest longTest = new BackgroundTest(50);
        Thread backgroundThread = 
            new Thread(new ThreadStart(longTest.RunLoop));
        backgroundThread.IsBackground = true;

        foregroundThread.Start();
        backgroundThread.Start();
    }
}

class BackgroundTest
{
    int maxIterations;

    public BackgroundTest(int maxIterations)
    {
        this.maxIterations = maxIterations;
    }

    public void RunLoop()
    {
        for (int i = 0; i < maxIterations; i++) {
            Console.WriteLine("{0} count: {1}", 
                Thread.CurrentThread.IsBackground ? 
                   "Background Thread" : "Foreground Thread", i);
            Thread.Sleep(250);
        }
        Console.WriteLine("{0} finished counting.", 
                          Thread.CurrentThread.IsBackground ? 
                          "Background Thread" : "Foreground Thread");
    }
}
// The example displays output like the following:
//    Foreground Thread count: 0
//    Background Thread count: 0
//    Background Thread count: 1
//    Foreground Thread count: 1
//    Foreground Thread count: 2
//    Background Thread count: 2
//    Foreground Thread count: 3
//    Background Thread count: 3
//    Background Thread count: 4
//    Foreground Thread count: 4
//    Foreground Thread count: 5
//    Background Thread count: 5
//    Foreground Thread count: 6
//    Background Thread count: 6
//    Background Thread count: 7
//    Foreground Thread count: 7
//    Background Thread count: 8
//    Foreground Thread count: 8
//    Foreground Thread count: 9
//    Background Thread count: 9
//    Background Thread count: 10
//    Foreground Thread count: 10
//    Background Thread count: 11
//    Foreground Thread finished counting.
open System.Threading

type BackgroundTest(maxIterations) =
    member _.RunLoop() =
        for i = 0 to maxIterations - 1 do
            printfn
                $"""{if Thread.CurrentThread.IsBackground then
                         "Background Thread"
                     else
                         "Foreground Thread"} count: {i}"""

            Thread.Sleep 250

        printfn
            $"""{if Thread.CurrentThread.IsBackground then
                     "Background Thread"
                 else
                     "Foreground Thread"} finished counting."""

let shortTest = BackgroundTest 10
let foregroundThread = Thread shortTest.RunLoop

let longTest = BackgroundTest 50
let backgroundThread = Thread longTest.RunLoop
backgroundThread.IsBackground <- true

foregroundThread.Start()
backgroundThread.Start()

// The example displays output like the following:
//    Foreground Thread count: 0
//    Background Thread count: 0
//    Background Thread count: 1
//    Foreground Thread count: 1
//    Foreground Thread count: 2
//    Background Thread count: 2
//    Foreground Thread count: 3
//    Background Thread count: 3
//    Background Thread count: 4
//    Foreground Thread count: 4
//    Foreground Thread count: 5
//    Background Thread count: 5
//    Foreground Thread count: 6
//    Background Thread count: 6
//    Background Thread count: 7
//    Foreground Thread count: 7
//    Background Thread count: 8
//    Foreground Thread count: 8
//    Foreground Thread count: 9
//    Background Thread count: 9
//    Background Thread count: 10
//    Foreground Thread count: 10
//    Background Thread count: 11
//    Foreground Thread finished counting.
Imports System.Threading

Public Module Example
    Public Sub Main()
        Dim shortTest As New BackgroundTest(10)
        Dim foregroundThread As New Thread(AddressOf shortTest.RunLoop)

        Dim longTest As New BackgroundTest(50)
        Dim backgroundThread As New Thread(AddressOf longTest.RunLoop)
        backgroundThread.IsBackground = True

        foregroundThread.Start()
        backgroundThread.Start()
    End Sub
End Module

Public Class BackgroundTest
    Dim maxIterations As Integer 

    Sub New(maximumIterations As Integer)
        maxIterations = maximumIterations
    End Sub

    Sub RunLoop()
        For i As Integer = 0 To maxIterations
            Console.WriteLine("{0} count: {1}", _
                    If(Thread.CurrentThread.IsBackground, 
                       "Background Thread", "Foreground Thread"), i)
            Thread.Sleep(250)
        Next 

        Console.WriteLine("{0} finished counting.", 
                          If(Thread.CurrentThread.IsBackground, 
                          "Background Thread", "Foreground Thread"))
    End Sub
End Class
' The example displays output like the following:
'    Foreground Thread count: 0
'    Background Thread count: 0
'    Background Thread count: 1
'    Foreground Thread count: 1
'    Foreground Thread count: 2
'    Background Thread count: 2
'    Foreground Thread count: 3
'    Background Thread count: 3
'    Background Thread count: 4
'    Foreground Thread count: 4
'    Foreground Thread count: 5
'    Background Thread count: 5
'    Foreground Thread count: 6
'    Background Thread count: 6
'    Background Thread count: 7
'    Foreground Thread count: 7
'    Background Thread count: 8
'    Foreground Thread count: 8
'    Foreground Thread count: 9
'    Background Thread count: 9
'    Background Thread count: 10
'    Foreground Thread count: 10
'    Background Thread count: 11
'    Foreground Thread finished counting.

Comentarios

Un subproceso es un subproceso en segundo plano o un subproceso en primer plano. Los subprocesos en segundo plano son idénticos a los subprocesos en primer plano, salvo que los subprocesos en segundo plano no impiden que un proceso termine. Una vez finalizados todos los subprocesos en primer plano que pertenecen a un proceso, Common Language Runtime finaliza el proceso. Los subprocesos en segundo plano restantes se detienen y no se completan.

De forma predeterminada, los siguientes subprocesos se ejecutan en primer plano (es decir, su IsBackground propiedad devuelve false):

  • El subproceso principal (o el subproceso principal de la aplicación).

  • Todos los hilos creados mediante una llamada a un Thread constructor de clase.

De forma predeterminada, los subprocesos siguientes se ejecutan en segundo plano (es decir, su IsBackground propiedad devuelve true):

  • Subprocesos del grupo de subprocesos, que son un grupo de subprocesos de trabajo mantenidos por el tiempo de ejecución. Puede configurar el grupo de subprocesos y programar el trabajo en los subprocesos del grupo de subprocesos mediante la clase ThreadPool.

    Nota:

    Las operaciones asincrónicas basadas en tareas se ejecutan automáticamente en subprocesos del grupo de subprocesos.

  • Todos los subprocesos que entran en el entorno de ejecución administrado desde código no administrado.

Se aplica a

Consulte también