Compartilhar via


Thread.IsBackground Propriedade

Definição

Obtém ou define um valor que indica se um thread é ou não um thread em segundo plano.

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 da propriedade

true se esse thread for ou se tornar um thread em segundo plano; caso contrário, false.

Exceções

O thread está morto.

Exemplos

O exemplo a seguir contrasta o comportamento de threads em primeiro plano e em segundo plano. Ele cria um thread em primeiro plano e um thread em segundo plano. O thread em primeiro plano mantém o processo em execução até concluir o for loop e terminar. No entanto, como mostra a saída do exemplo, como o thread de primeiro plano terminou a execução, o processo é encerrado antes que o thread em segundo plano tenha concluído a execução.

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.

Comentários

Um thread é um thread em segundo plano ou um thread em primeiro plano. Os threads em segundo plano são idênticos aos threads de primeiro plano, exceto que os threads em segundo plano não impedem que um processo seja encerrado. Depois que todos os threads de primeiro plano pertencentes a um processo tiverem sido encerrados, o common language runtime encerrará o processo. Todos os threads restantes em segundo plano são interrompidos e não são concluídos.

Por padrão, os seguintes threads são executados em primeiro plano (ou seja, sua IsBackground propriedade retorna false):

  • O thread primário (ou thread do aplicativo principal).

  • Todos os threads criados chamando um Thread construtor de classe.

Por padrão, os threads a seguir são executados em segundo plano (ou seja, sua IsBackground propriedade retorna true):

  • Threads do pool de threads, que são um pool de threads de trabalho mantidos pelo runtime. Você pode configurar o pool de threads e agendar o trabalho nos threads do pool de threads usando a classe ThreadPool.

    Observação

    As operações assíncronas baseadas em tarefa são executadas automaticamente nos threads do pool de threads.

  • Todas as threads que entram no ambiente de execução gerenciada a partir do código não gerenciado.

Aplica-se a

Confira também