Demonstra Passo a passo: Executa uma operação em segundo plano

Se você tem uma operação que levará muito tempo para concluir, e você não deseja causar atrasos na sua interface de usuário, você pode usar o BackgroundWorker classe para executar a operação em outro segmento.

Para obter uma listagem completa do código usada neste exemplo, consulte Como: Executar uma operação em segundo plano.

ObservaçãoObservação

As caixas de diálogo e comandos de menu demonstradas podem ser diferentes daqueles descritos na Ajuda, dependendo das configurações ativas ou configurações de edição. Para alterar as configurações, escolha Import and Export Settings sobre o Ferramentas menu. Para obter mais informações, consulte Trabalhando com configurações.

Para executar uma operação no plano de fundo

  1. Com o formulário ativo no Windows Forms Designer, arraste dois Button controla a partir de Toolbox para o formulário e defina a Name e Text Propriedades dos botões de acordo com a tabela a seguir.

    Button

    Nome

    Texto

    button1

    startBtn

    Iniciar

    button2

    cancelBtn

    Cancel

  2. Abrir o Toolbox, clique o componentes guia e, em seguida, arraste o BackgroundWorker componente em seu formulário.

    O backgroundWorker1 componente aparecer o Component Tray.

  3. No Propriedades janela, defina a WorkerSupportsCancellation propriedade para true.

  4. No Propriedades janela, clique no eventos botão e, em seguida, clique duas vezes o DoWork e RunWorkerCompleted eventos para criar manipuladores de eventos.

  5. Insira seu código demorado para a DoWork manipulador de eventos.

  6. Quaisquer parâmetros necessários para a operação de extrair o Argument propriedade da DoWorkEventArgs parâmetro.

  7. Atribuir o resultado da computação para o Result propriedade da DoWorkEventArgs.

    Isso será estar disponível para o RunWorkerCompleted manipulador de eventos.

    Private Sub backgroundWorker1_DoWork( _
    sender As Object, e As DoWorkEventArgs) _
    Handles backgroundWorker1.DoWork
    
       ' Do not access the form's BackgroundWorker reference directly.
       ' Instead, use the reference provided by the sender parameter.
       Dim bw As BackgroundWorker = CType( sender, BackgroundWorker )
    
       ' Extract the argument.
       Dim arg As Integer = Fix(e.Argument)
    
       ' Start the time-consuming operation.
       e.Result = TimeConsumingOperation(bw, arg)
    
       ' If the operation was canceled by the user, 
       ' set the DoWorkEventArgs.Cancel property to true.
       If bw.CancellationPending Then
          e.Cancel = True
       End If
    
    End Sub   
    
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        // Do not access the form's BackgroundWorker reference directly.
        // Instead, use the reference provided by the sender parameter.
        BackgroundWorker bw = sender as BackgroundWorker;
    
        // Extract the argument.
        int arg = (int)e.Argument;
    
        // Start the time-consuming operation.
        e.Result = TimeConsumingOperation(bw, arg);
    
        // If the operation was canceled by the user, 
        // set the DoWorkEventArgs.Cancel property to true.
        if (bw.CancellationPending)
        {
            e.Cancel = true;
        }
    }
    
  8. Insira o código para recuperar o resultado da sua operação de RunWorkerCompleted manipulador de eventos.

    ' This event handler demonstrates how to interpret 
    ' the outcome of the asynchronous operation implemented
    ' in the DoWork event handler.
    Private Sub backgroundWorker1_RunWorkerCompleted( _
    sender As Object, e As RunWorkerCompletedEventArgs) _
    Handles backgroundWorker1.RunWorkerCompleted
    
       If e.Cancelled Then
          ' The user canceled the operation.
          MessageBox.Show("Operation was canceled")
       ElseIf (e.Error IsNot Nothing) Then
          ' There was an error during the operation.
          Dim msg As String = String.Format("An error occurred: {0}", e.Error.Message)
          MessageBox.Show(msg)
       Else
          ' The operation completed normally.
          Dim msg As String = String.Format("Result = {0}", e.Result)
          MessageBox.Show(msg)
       End If
    End Sub   
    
    // This event handler demonstrates how to interpret 
    // the outcome of the asynchronous operation implemented
    // in the DoWork event handler.
    private void backgroundWorker1_RunWorkerCompleted(
        object sender, 
        RunWorkerCompletedEventArgs e)
    {   
        if (e.Cancelled)
        {
            // The user canceled the operation.
            MessageBox.Show("Operation was canceled");
        }
        else if (e.Error != null)
        {
            // There was an error during the operation.
            string msg = String.Format("An error occurred: {0}", e.Error.Message);
            MessageBox.Show(msg);
        }
        else
        {
            // The operation completed normally.
            string msg = String.Format("Result = {0}", e.Result);
            MessageBox.Show(msg);
        }
    }
    
  9. Implemente o método TimeConsumingOperation.

    ' This method models an operation that may take a long time 
    ' to run. It can be cancelled, it can raise an exception,
    ' or it can exit normally and return a result. These outcomes
    ' are chosen randomly.
    Private Function TimeConsumingOperation( _
    bw As BackgroundWorker, _
    sleepPeriod As Integer) As Integer
    
       Dim result As Integer = 0
    
       Dim rand As New Random()
    
         While Not bw.CancellationPending
             Dim [exit] As Boolean = False
    
             Select Case rand.Next(3)
                 ' Raise an exception.
                 Case 0
                     Throw New Exception("An error condition occurred.")
                     Exit While
    
                     ' Sleep for the number of milliseconds
                     ' specified by the sleepPeriod parameter.
                 Case 1
                     Thread.Sleep(sleepPeriod)
                     Exit While
    
                     ' Exit and return normally.
                 Case 2
                     result = 23
                     [exit] = True
                     Exit While
    
                 Case Else
                     Exit While
             End Select
    
             If [exit] Then
                 Exit While
             End If
         End While
    
       Return result
    End Function
    
    // This method models an operation that may take a long time 
    // to run. It can be cancelled, it can raise an exception,
    // or it can exit normally and return a result. These outcomes
    // are chosen randomly.
    private int TimeConsumingOperation( 
        BackgroundWorker bw, 
        int sleepPeriod )
    {
        int result = 0;
    
        Random rand = new Random();
    
        while (!bw.CancellationPending)
        {
            bool exit = false;
    
            switch (rand.Next(3))
            {
                // Raise an exception.
                case 0:
                {
                    throw new Exception("An error condition occurred.");
                    break;
                }
    
                // Sleep for the number of milliseconds
                // specified by the sleepPeriod parameter.
                case 1:
                {
                    Thread.Sleep(sleepPeriod);
                    break;
                }
    
                // Exit and return normally.
                case 2:
                {
                    result = 23;
                    exit = true;
                    break;
                }
    
                default:
                {
                    break;
                }
            }
    
            if( exit )
            {
                break;
            }
        }
    
        return result;
    }
    
  10. No Windows Forms Designer, clique duas vezes em startButton para criar o Click manipulador de eventos.

  11. Chamar o RunWorkerAsync método na Click o manipulador de eventos para startButton.

    Private Sub startButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles startBtn.Click
        Me.backgroundWorker1.RunWorkerAsync(2000)
    End Sub
    
    private void startBtn_Click(object sender, EventArgs e)
    {
        this.backgroundWorker1.RunWorkerAsync(2000);
    }
    
  12. No Windows Forms Designer, clique duas vezes em cancelButton para criar o Click manipulador de eventos.

  13. Chamar o CancelAsync método na Click o manipulador de eventos para cancelButton.

    Private Sub cancelButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cancelBtn.Click
        Me.backgroundWorker1.CancelAsync()
    End Sub
    
    private void cancelBtn_Click(object sender, EventArgs e)
    {
        this.backgroundWorker1.CancelAsync();
    }
    
  14. Na parte superior do arquivo, importe os namespaces System.ComponentModel e System. Threading.

    Imports System
    Imports System.ComponentModel
    Imports System.Drawing
    Imports System.Threading
    Imports System.Windows.Forms
    
    using System;
    using System.ComponentModel;
    using System.Drawing;
    using System.Threading;
    using System.Windows.Forms;
    
  15. Pressione F6 para criar a solução e, em seguida, pressione CTRL-F5 para executar o aplicativo fora do depurador.

ObservaçãoObservação

Se você pressionar F5 para executar o aplicativo sob o depurador, a exceção gerada na TimeConsumingOperation método é detectado e exibido pelo depurador. Quando você executar o aplicativo fora do depurador, o BackgroundWorker manipula a exceção e armazena em cache na Error propriedade da RunWorkerCompletedEventArgs.

  1. Clique o Iniciar para executar uma operação assíncrona e, em seguida, clique na Cancelar botão para interromper uma operação assíncrona em execução.

    O resultado de cada operação é exibido em um MessageBox.

Próximas etapas

Consulte também

Tarefas

Como: Implementar um formulário que usa uma operação de plano de fundo

Como: Executar uma operação em segundo plano

Referência

BackgroundWorker

DoWorkEventArgs

Outros recursos

Componente BackgroundWorker