BackgroundWorker Classe (System - ComponentModel)
BackgroundWorker Classe (System - ComponentModel)
BackgroundWorker Classe
Referência
Definição
Namespace: System.ComponentModel
Assembly: System.ComponentModel.EventBasedAsync.dll
C#
Exemplos
O exemplo de código a BackgroundWorker seguir demonstra os conceitos básicos da
classe para executar uma operação demorada de forma assíncrona. A ilustração a seguir
mostra um exemplo da saída.
Para experimentar esse código, crie um aplicativo Windows Forms. Adicione um Label
controle chamado resultLabel e adicione dois Button controles chamados
startAsyncButton e cancelAsyncButton . Crie Click manipuladores de eventos para
C#
https://learn.microsoft.com/pt-br/dotnet/api/system.componentmodel.backgroundworker?view=net-7.0 1/13
28/03/2023 14:27 BackgroundWorker Classe (System.ComponentModel) | Microsoft Learn
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace BackgroundWorkerSimple
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
C#
using System;
using System.Collections;
using System.ComponentModel;
https://learn.microsoft.com/pt-br/dotnet/api/system.componentmodel.backgroundworker?view=net-7.0 3/13
28/03/2023 14:27 BackgroundWorker Classe (System.ComponentModel) | Microsoft Learn
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
namespace BackgroundWorkerExample
{
public class FibonacciForm : System.Windows.Forms.Form
{
private int numberToCompute = 0;
private int highestPercentageReached = 0;
public FibonacciForm()
{
InitializeComponent();
InitializeBackgroundWorker();
}
this.cancelAsyncButton.Enabled = true;
resultLabel.Text = "Canceled";
}
else
{
// Finally, handle the case where the operation
// succeeded.
resultLabel.Text = e.Result.ToString();
}
// This is the method that does the actual work. For this
// example, it computes a Fibonacci number and
// reports progress as it does its work.
long ComputeFibonacci(int n, BackgroundWorker worker,
DoWorkEventArgs e)
{
// The parameter n must be >= 0 and <= 91.
// Fib(n), with n > 91, overflows a long.
if ((n < 0) || (n > 91))
{
throw new ArgumentException(
"value must be >= 0 and <= 91", "n");
}
long result = 0;
if (worker.CancellationPending)
{
e.Cancel = true;
https://learn.microsoft.com/pt-br/dotnet/api/system.componentmodel.backgroundworker?view=net-7.0 6/13
28/03/2023 14:27 BackgroundWorker Classe (System.ComponentModel) | Microsoft Learn
}
else
{
if (n < 2)
{
result = 1;
}
else
{
result = ComputeFibonacci(n - 1, worker, e) +
ComputeFibonacci(n - 2, worker, e);
}
return result;
}
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(80, 20);
this.numericUpDown1.TabIndex = 0;
this.numericUpDown1.Value = new System.Decimal(new int[] {
1,
0,
0,
0});
//
// startAsyncButton
//
this.startAsyncButton.Location = new System.Drawing.Point(16,
72);
this.startAsyncButton.Name = "startAsyncButton";
this.startAsyncButton.Size = new System.Drawing.Size(120, 23);
this.startAsyncButton.TabIndex = 1;
this.startAsyncButton.Text = "Start Async";
this.startAsyncButton.Click += new
System.EventHandler(this.startAsyncButton_Click);
//
// cancelAsyncButton
//
this.cancelAsyncButton.Enabled = false;
this.cancelAsyncButton.Location = new System.Drawing.Point(153,
72);
this.cancelAsyncButton.Name = "cancelAsyncButton";
this.cancelAsyncButton.Size = new System.Drawing.Size(119, 23);
this.cancelAsyncButton.TabIndex = 2;
this.cancelAsyncButton.Text = "Cancel Async";
this.cancelAsyncButton.Click += new
System.EventHandler(this.cancelAsyncButton_Click);
//
// resultLabel
//
this.resultLabel.BorderStyle =
System.Windows.Forms.BorderStyle.Fixed3D;
this.resultLabel.Location = new System.Drawing.Point(112, 16);
this.resultLabel.Name = "resultLabel";
this.resultLabel.Size = new System.Drawing.Size(160, 23);
this.resultLabel.TabIndex = 3;
this.resultLabel.Text = "(no result)";
this.resultLabel.TextAlign =
System.Drawing.ContentAlignment.MiddleCenter;
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(18, 48);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(256, 8);
this.progressBar1.Step = 2;
this.progressBar1.TabIndex = 4;
//
// backgroundWorker1
//
this.backgroundWorker1.WorkerReportsProgress = true;
https://learn.microsoft.com/pt-br/dotnet/api/system.componentmodel.backgroundworker?view=net-7.0 8/13
28/03/2023 14:27 BackgroundWorker Classe (System.ComponentModel) | Microsoft Learn
this.backgroundWorker1.WorkerSupportsCancellation = true;
//
// FibonacciForm
//
this.ClientSize = new System.Drawing.Size(292, 118);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.resultLabel);
this.Controls.Add(this.cancelAsyncButton);
this.Controls.Add(this.startAsyncButton);
this.Controls.Add(this.numericUpDown1);
this.Name = "FibonacciForm";
this.Text = "Fibonacci Calculator";
((System.ComponentModel.ISupportInitialize)
(this.numericUpDown1)).EndInit();
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new FibonacciForm());
}
}
}
Comentários
A BackgroundWorker classe permite que você execute uma operação em um thread
separado e dedicado. Operações demoradas, como downloads e transações de banco
de dados, podem fazer com que a interface do usuário pareça ter parado de responder
enquanto estão em execução. Quando você deseja uma interface do usuário responsiva
e enfrenta longos atrasos associados a essas operações, a BackgroundWorker classe
fornece uma solução conveniente.
7 Observação
Você deve ter cuidado para não manipular nenhum objeto de interface do usuário
em seu DoWork manipulador de eventos. Em vez disso, comunique-se com a
interface do usuário por meio dos ProgressChanged eventos e
RunWorkerCompleted .
Para saber mais sobre BackgroundWorker, consulte Como executar uma operação em
segundo plano.
Construtores
BackgroundWorker() Inicializa uma nova instância da classe BackgroundWorker.
Propriedades
CancellationPending Obtém um valor que indica se o aplicativo solicitou o
cancelamento de uma operação em segundo plano.
https://learn.microsoft.com/pt-br/dotnet/api/system.componentmodel.backgroundworker?view=net-7.0 10/13
28/03/2023 14:27 BackgroundWorker Classe (System.ComponentModel) | Microsoft Learn
Métodos
CancelAsync() Solicita o cancelamento de uma operação pendente em
segundo plano.
GetLifetimeService() Obsoleto.
Recupera o objeto de serviço de tempo de vida atual que
controla a política de ciclo de vida para esta instância.
(Herdado de MarshalByRefObject)
InitializeLifetimeService() Obsoleto.
Obtém um objeto de serviço de tempo de vida para controlar a
política de tempo de vida para essa instância.
(Herdado de MarshalByRefObject)
(Herdado de Object)
Eventos
Disposed Ocorre quando o componente é disposto por uma chamada ao
método Dispose().
(Herdado de Component)
Aplica-se a
Produto Versões
.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
.NET Framework 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
https://learn.microsoft.com/pt-br/dotnet/api/system.componentmodel.backgroundworker?view=net-7.0 12/13
28/03/2023 14:27 BackgroundWorker Classe (System.ComponentModel) | Microsoft Learn
Produto Versões
UWP 10.0
Xamarin.iOS 10.8
Xamarin.Mac 3.0
Confira também
Como: Executar uma operação em segundo plano
Práticas recomendadas de threading gerenciado
Como: Como baixar um arquivo em segundo plano
https://learn.microsoft.com/pt-br/dotnet/api/system.componentmodel.backgroundworker?view=net-7.0 13/13