Поделиться через


BackgroundWorker.ReportProgress Метод

Определение

Вызывает событие ProgressChanged.

Перегрузки

Имя Описание
ReportProgress(Int32)

Вызывает событие ProgressChanged.

ReportProgress(Int32, Object)

Вызывает событие ProgressChanged.

ReportProgress(Int32)

Исходный код:
BackgroundWorker.cs
Исходный код:
BackgroundWorker.cs
Исходный код:
BackgroundWorker.cs
Исходный код:
BackgroundWorker.cs
Исходный код:
BackgroundWorker.cs

Вызывает событие ProgressChanged.

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

Параметры

percentProgress
Int32

Процент от 0 до 100 фоновых операций, завершенных.

Исключения

Для свойства WorkerReportsProgress задано значение false.

Примеры

В следующем примере кода показано использование ReportProgress метода для отчета о ходе асинхронной операции пользователю. Этот пример кода является частью более крупного примера, предоставленного для BackgroundWorker класса.

// 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
{
    result = n < 2
        ? 1
        : ComputeFibonacci(n - 1, worker, e) +
                 ComputeFibonacci(n - 2, worker, e);

    // Report progress as a percentage of the total task.
    int percentComplete =
        (int)(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

Комментарии

Если требуется фоновая операция для отчета о ходе выполнения, можно вызвать ReportProgress метод для вызова ProgressChanged события. WorkerReportsProgress Значение свойства должно быть trueили ReportProgress будет вызыватьсяInvalidOperationException.

Это до вас, чтобы реализовать значимый способ измерения хода выполнения фоновой операции в процентах от итоговой задачи, завершенной.

ReportProgress Вызов метода является асинхронным и возвращается немедленно. Обработчик ProgressChanged событий выполняется в потоке, который создал объект BackgroundWorker.

См. также раздел

Применяется к

ReportProgress(Int32, Object)

Исходный код:
BackgroundWorker.cs
Исходный код:
BackgroundWorker.cs
Исходный код:
BackgroundWorker.cs
Исходный код:
BackgroundWorker.cs
Исходный код:
BackgroundWorker.cs

Вызывает событие 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)

Параметры

percentProgress
Int32

Процент от 0 до 100 фоновых операций, завершенных.

userState
Object

Уникальный Object , указывающий состояние пользователя. Возвращается в качестве UserState свойства ProgressChangedEventArgsобъекта .

Исключения

Для свойства WorkerReportsProgress задано значение false.

Примеры

В следующем примере кода показано использование ReportProgress метода для отчета о ходе асинхронной операции пользователю. Этот пример кода является частью более крупного примера, предоставленного для ToolStripProgressBar класса.

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

Комментарии

Если требуется фоновая операция для отчета о ходе выполнения, можно вызвать ReportProgress метод для вызова ProgressChanged события. WorkerReportsProgress Значение свойства должно или trueReportProgress вызовет InvalidOperationExceptionисключение.

Это до вас, чтобы реализовать значимый способ измерения хода выполнения фоновой операции в процентах от итоговой задачи, завершенной.

См. также раздел

Применяется к