BackgroundWorker.ReportProgress Método

Definição

Aciona o evento ProgressChanged.

Sobrecargas

ReportProgress(Int32)

Aciona o evento ProgressChanged.

ReportProgress(Int32, Object)

Aciona o evento ProgressChanged.

ReportProgress(Int32)

Origem:
BackgroundWorker.cs
Origem:
BackgroundWorker.cs
Origem:
BackgroundWorker.cs

Aciona o evento ProgressChanged.

public:
 void ReportProgress(int percentProgress);
public void ReportProgress (int percentProgress);
member this.ReportProgress : int -> unit
Public Sub ReportProgress (percentProgress As Integer)

Parâmetros

percentProgress
Int32

O percentual, de 0 a 100, da operação em segundo plano concluída.

Exceções

A propriedade WorkerReportsProgress está definida como false.

Exemplos

O exemplo de código a seguir demonstra o uso do ReportProgress método para relatar o progresso de uma operação assíncrona para o usuário. Este exemplo de código faz parte de um exemplo maior fornecido para a BackgroundWorker classe .

// Abort the operation if the user has cancelled.
// Note that a call to CancelAsync may have set 
// CancellationPending to true just after the
// last invocation of this method exits, so this 
// code will not have the opportunity to set the 
// DoWorkEventArgs.Cancel flag to true. This means
// that RunWorkerCompletedEventArgs.Cancelled will
// not be set to true in your RunWorkerCompleted
// event handler. This is a race condition.
if ( worker->CancellationPending )
{
   e->Cancel = true;
}
else
{
   if ( n < 2 )
   {
      result = 1;
   }
   else
   {
      result = ComputeFibonacci( n - 1, worker, e ) + ComputeFibonacci( n - 2, worker, e );
   }

   // Report progress as a percentage of the total task.
   int percentComplete = (int)((float)n / (float)numberToCompute * 100);
   if ( percentComplete > highestPercentageReached )
   {
      highestPercentageReached = percentComplete;
      worker->ReportProgress( percentComplete );
   }
}
// Abort the operation if the user has canceled.
// Note that a call to CancelAsync may have set 
// CancellationPending to true just after the
// last invocation of this method exits, so this 
// code will not have the opportunity to set the 
// DoWorkEventArgs.Cancel flag to true. This means
// that RunWorkerCompletedEventArgs.Cancelled will
// not be set to true in your RunWorkerCompleted
// event handler. This is a race condition.

if (worker.CancellationPending)
{   
    e.Cancel = true;
}
else
{   
    if (n < 2)
    {   
        result = 1;
    }
    else
    {   
        result = ComputeFibonacci(n - 1, worker, e) + 
                 ComputeFibonacci(n - 2, worker, e);
    }

    // Report progress as a percentage of the total task.
    int percentComplete = 
        (int)((float)n / (float)numberToCompute * 100);
    if (percentComplete > highestPercentageReached)
    {
        highestPercentageReached = percentComplete;
        worker.ReportProgress(percentComplete);
    }
}
' Abort the operation if the user has canceled.
' Note that a call to CancelAsync may have set 
' CancellationPending to true just after the
' last invocation of this method exits, so this 
' code will not have the opportunity to set the 
' DoWorkEventArgs.Cancel flag to true. This means
' that RunWorkerCompletedEventArgs.Cancelled will
' not be set to true in your RunWorkerCompleted
' event handler. This is a race condition.
If worker.CancellationPending Then
    e.Cancel = True
Else
    If n < 2 Then
        result = 1
    Else
        result = ComputeFibonacci(n - 1, worker, e) + _
                 ComputeFibonacci(n - 2, worker, e)
    End If

    ' Report progress as a percentage of the total task.
    Dim percentComplete As Integer = _
        CSng(n) / CSng(numberToCompute) * 100
    If percentComplete > highestPercentageReached Then
        highestPercentageReached = percentComplete
        worker.ReportProgress(percentComplete)
    End If

End If

Comentários

Se você precisar da operação em segundo plano para relatar seu progresso, poderá chamar o ReportProgress método para acionar o ProgressChanged evento. O valor da WorkerReportsProgress propriedade deve ser trueou ReportProgress gerará um InvalidOperationException.

Cabe a você implementar uma maneira significativa de medir o progresso da operação em segundo plano como uma porcentagem do total de tarefas concluídas.

A chamada para o método é assíncrona ReportProgress e retorna imediatamente. O ProgressChanged manipulador de eventos é executado no thread que criou o BackgroundWorker.

Confira também

Aplica-se a

ReportProgress(Int32, Object)

Origem:
BackgroundWorker.cs
Origem:
BackgroundWorker.cs
Origem:
BackgroundWorker.cs

Aciona o evento ProgressChanged.

public:
 void ReportProgress(int percentProgress, System::Object ^ userState);
public void ReportProgress (int percentProgress, object userState);
public void ReportProgress (int percentProgress, object? userState);
member this.ReportProgress : int * obj -> unit
Public Sub ReportProgress (percentProgress As Integer, userState As Object)

Parâmetros

percentProgress
Int32

O percentual, de 0 a 100, da operação em segundo plano concluída.

userState
Object

Um Object exclusivo que indica o estado do usuário. Retornado como a propriedade UserState do ProgressChangedEventArgs.

Exceções

A propriedade WorkerReportsProgress está definida como false.

Exemplos

O exemplo de código a seguir demonstra o uso do ReportProgress método para relatar o progresso de uma operação assíncrona para o usuário. Este exemplo de código faz parte de um exemplo maior fornecido para a ToolStripProgressBar classe .

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    // This method will run on a thread other than the UI thread.
    // Be sure not to manipulate any Windows Forms controls created
    // on the UI thread from this method.
    backgroundWorker.ReportProgress(0, "Working...");
    Decimal lastlast = 0;
    Decimal last = 1;
    Decimal current;
    if (requestedCount >= 1)
    { AppendNumber(0); }
    if (requestedCount >= 2)
    { AppendNumber(1); }
    for (int i = 2; i < requestedCount; ++i)
    {
        // Calculate the number.
        checked { current = lastlast + last; }
        // Introduce some delay to simulate a more complicated calculation.
        System.Threading.Thread.Sleep(100);
        AppendNumber(current);
        backgroundWorker.ReportProgress((100 * i) / requestedCount, "Working...");
        // Get ready for the next iteration.
        lastlast = last;
        last = current;
    }

    backgroundWorker.ReportProgress(100, "Complete!");
}
Private Sub backgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs)
   ' This method will run on a thread other than the UI thread.
   ' Be sure not to manipulate any Windows Forms controls created
   ' on the UI thread from this method.
   backgroundWorker.ReportProgress(0, "Working...")
   Dim lastlast As [Decimal] = 0
   Dim last As [Decimal] = 1
   Dim current As [Decimal]
   If requestedCount >= 1 Then
      AppendNumber(0)
   End If
   If requestedCount >= 2 Then
      AppendNumber(1)
   End If
   Dim i As Integer
   
   While i < requestedCount
      ' Calculate the number.
      current = lastlast + last
      ' Introduce some delay to simulate a more complicated calculation.
      System.Threading.Thread.Sleep(100)
      AppendNumber(current)
      backgroundWorker.ReportProgress(100 * i / requestedCount, "Working...")
      ' Get ready for the next iteration.
      lastlast = last
      last = current
      i += 1
   End While
   
   
   backgroundWorker.ReportProgress(100, "Complete!")
 End Sub

Comentários

Se você precisar da operação em segundo plano para relatar seu progresso, poderá chamar o ReportProgress método para acionar o ProgressChanged evento. O valor da WorkerReportsProgress propriedade deve trueou ReportProgress gerará um InvalidOperationException.

Cabe a você implementar uma maneira significativa de medir o progresso da operação em segundo plano como uma porcentagem do total de tarefas concluídas.

Confira também

Aplica-se a