.NET Framework 클래스 라이브러리
BackgroundWorker.RunWorkerCompleted 이벤트

참고: 이 이벤트는 .NET Framework 버전 2.0에서 새로 추가되었습니다.

백그라운드 작업이 완료되거나 취소되거나 예외를 발생시켰을 때 발생합니다.

네임스페이스: System.ComponentModel
어셈블리: System(system.dll)

구문

Visual Basic(선언)
Public Event RunWorkerCompleted As RunWorkerCompletedEventHandler
Visual Basic(사용법)
Dim instance As BackgroundWorker
Dim handler As RunWorkerCompletedEventHandler

AddHandler instance.RunWorkerCompleted, handler
C#
public event RunWorkerCompletedEventHandler RunWorkerCompleted
C++
public:
event RunWorkerCompletedEventHandler^ RunWorkerCompleted {
    void add (RunWorkerCompletedEventHandler^ value);
    void remove (RunWorkerCompletedEventHandler^ value);
}
J#
/** @event */
public void add_RunWorkerCompleted (RunWorkerCompletedEventHandler value)

/** @event */
public void remove_RunWorkerCompleted (RunWorkerCompletedEventHandler value)
JScript
JScript에서는 이벤트를 사용할 수 있지만 새로 선언할 수는 없습니다.
설명

이 이벤트는 DoWork 이벤트 처리기가 반환될 때 발생합니다.

작업이 성공적으로 완료되고 결과가 DoWork 이벤트 처리기에 할당되면 RunWorkerCompletedEventArgs.Result 속성을 통해 결과에 액세스할 수 있습니다.

System.ComponentModel.RunWorkerCompletedEventArgsError 속성은 작업에서 예외를 throw했음을 나타냅니다.

System.ComponentModel.RunWorkerCompletedEventArgsCancelled 속성은 백그라운드 작업에서 취소 요청을 처리했는지 여부를 나타냅니다. DoWork 이벤트 처리기의 코드에서 CancellationPending 플래그를 확인하고 System.ComponentModel.DoWorkEventArgsCancel 플래그를 true로 설정하여 취소 요청을 감지하면 System.ComponentModel.RunWorkerCompletedEventArgsCancelled 플래그도 true로 설정됩니다.

Caution note주의

DoWork 이벤트 처리기의 코드에서는 취소가 요청되면 작업을 종료할 수 있으며, 폴링 루프에서 true로 설정되는 CancellationPending을 놓칠 수 있습니다. 이 경우 취소가 요청된 경우에도 RunWorkerCompleted 이벤트 처리기에 있는 System.ComponentModel.RunWorkerCompletedEventArgsCancelled 플래그가 true로 설정되지 않습니다. 이러한 상황을 경쟁 조건이라고 하는데, 경쟁 조건은 다중 스레드 프로그래밍에서 제기되는 일반적인 문제입니다. 다중 스레드 디자인 문제에 대한 자세한 내용은 관리되는 스레딩을 구현하는 최선의 방법을 참조하십시오.

RunWorkerCompleted 이벤트 처리기는 RunWorkerCompletedEventArgs.Result 속성에 액세스하기 전에 항상 AsyncCompletedEventArgs.ErrorAsyncCompletedEventArgs.Cancelled 속성을 확인해야 합니다. 예외가 발생하거나 작업이 취소된 경우 RunWorkerCompletedEventArgs.Result 속성에 액세스하면 예외가 발생합니다.

예제

다음 코드 예제에서는 RunWorkerCompleted 이벤트를 사용하여 비동기 작업의 결과를 처리하는 방법을 보여 줍니다. 이 코드 예제는 BackgroundWorker 클래스에 대해 제공되는 보다 큰 예제의 일부입니다.

Visual Basic
' This event handler deals with the results of the
' background operation.
Private Sub backgroundWorker1_RunWorkerCompleted( _
ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
Handles backgroundWorker1.RunWorkerCompleted

    ' First, handle the case where an exception was thrown.
    If Not (e.Error Is Nothing) Then
        MessageBox.Show(e.Error.Message)
    ElseIf e.Cancelled Then
        ' Next, handle the case where the user canceled the 
        ' operation.
        ' Note that due to a race condition in 
        ' the DoWork event handler, the Cancelled
        ' flag may not have been set, even though
        ' CancelAsync was called.
        resultLabel.Text = "Canceled"
    Else
        ' Finally, handle the case where the operation succeeded.
        resultLabel.Text = e.Result.ToString()
    End If

    ' Enable the UpDown control.
    Me.numericUpDown1.Enabled = True

    ' Enable the Start button.
    startAsyncButton.Enabled = True

    ' Disable the Cancel button.
    cancelAsyncButton.Enabled = False
End Sub 'backgroundWorker1_RunWorkerCompleted
C#
// This event handler deals with the results of the
// background operation.
private void backgroundWorker1_RunWorkerCompleted(
    object sender, RunWorkerCompletedEventArgs e)
{
    // First, handle the case where an exception was thrown.
    if (e.Error != null)
    {
        MessageBox.Show(e.Error.Message);
    }
    else if (e.Cancelled)
    {
        // Next, handle the case where the user canceled 
        // the operation.
        // Note that due to a race condition in 
        // the DoWork event handler, the Cancelled
        // flag may not have been set, even though
        // CancelAsync was called.
        resultLabel.Text = "Canceled";
    }
    else
    {
        // Finally, handle the case where the operation 
        // succeeded.
        resultLabel.Text = e.Result.ToString();
    }

    // Enable the UpDown control.
    this.numericUpDown1.Enabled = true;

    // Enable the Start button.
    startAsyncButton.Enabled = true;

    // Disable the Cancel button.
    cancelAsyncButton.Enabled = false;
}
C++
// This event handler deals with the results of the
// background operation.
void backgroundWorker1_RunWorkerCompleted( Object^ /*sender*/, RunWorkerCompletedEventArgs^ e )
{
   // First, handle the case where an exception was thrown.
   if ( e->Error != nullptr )
   {
      MessageBox::Show( e->Error->Message );
   }
   else
   if ( e->Cancelled )
   {
      // Next, handle the case where the user cancelled 
      // the operation.
      // Note that due to a race condition in 
      // the DoWork event handler, the Cancelled
      // flag may not have been set, even though
      // CancelAsync was called.
      resultLabel->Text = "Cancelled";
   }
   else
   {
      // Finally, handle the case where the operation 
      // succeeded.
      resultLabel->Text = e->Result->ToString();
   }

   // Enable the UpDown control.
   this->numericUpDown1->Enabled = true;

   // Enable the Start button.
   startAsyncButton->Enabled = true;

   // Disable the Cancel button.
   cancelAsyncButton->Enabled = false;
}
J#
// This event handler deals with the results of the
// background operation.
private void backgroundWorker1_RunWorkerCompleted(Object sender,
    RunWorkerCompletedEventArgs e)
{
    // First, handle the case where an exception was thrown.
    if (e.get_Error() != null) {
    
        MessageBox.Show(e.get_Error().get_Message());
    }
    else {
    
        if (e.get_Cancelled()) {
        
            // Next, handle the case where the user cancelled 
            // the operation.
            // Note that due to a race condition in 
            // the DoWork event handler, the Cancelled
            // flag may not have been set, even though
            // CancelAsync was called.
            resultLabel.set_Text("Cancelled");
        }
        else {
        
            // Finally, handle the case where the operation 
            // succeeded.
            resultLabel.set_Text(e.get_Result().ToString());
        }
    }

    // Enable the UpDown control.
    this.numericUpDown1.set_Enabled(true);

    // Enable the Start button.
    startAsyncButton.set_Enabled(true);

    // Disable the Cancel button.
    cancelAsyncButton.set_Enabled(false);
} //backgroundWorker1_RunWorkerCompleted
플랫폼

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0에서 지원
참고 항목

태그 :


Page view tracker