BackgroundWorker 구성 요소 개요

일반적으로 수행하는 작업 중에는 실행 시간이 오래 걸릴 수 있는 것들이 많습니다. 예를 들면 다음과 같습니다.

  • 이미지 다운로드

  • 웹 서비스 호출

  • 파일 다운로드 및 업로드(피어 투 피어 애플리케이션용 파일 포함)

  • 복잡한 로컬 계산

  • 데이터베이스 트랜잭션

  • 로컬 디스크 액세스(메모리 액세스에 비해 속도가 느림)

이러한 작업을 수행하는 동안에는 사용자 인터페이스가 차단될 수 있습니다. 응답성이 뛰어난 UI가 필요한데 이러한 작업과 관련하여 지연이 길어지는 경우 BackgroundWorker 구성 요소를 사용하면 문제를 편리하게 해결할 수 있습니다.

BackgroundWorker 구성 요소는 애플리케이션의 주 UI 스레드와는 다른 스레드에서 시간이 많이 걸리는 작업을 "백그라운드"에서 비동기식으로 실행하는 기능을 제공합니다. BackgroundWorker를 사용하려는 경우 백그라운드에서 실행하려는 시간이 많이 걸리는 작업자 프로세스를 지정한 다음 RunWorkerAsync 메서드만 호출하면 됩니다. 호출 스레드는 계속 정상적으로 실행되며 작업자 메서드는 비동기식으로 실행됩니다. 메서드가 완료되면 BackgroundWorkerRunWorkerCompleted 이벤트를 발생시켜 호출 스레드에 경고를 표시합니다. 이 이벤트는 필요에 따라 작업 결과를 포함합니다.

BackgroundWorker 구성 요소는 구성 요소도구 상자 탭에서 사용할 수 있습니다.BackgroundWorker을(를) 폼에 추가하려면 BackgroundWorker 구성 요소를 폼으로 끌어다 놓습니다. 그러면 구성 요소가 구성 요소 트레이에 표시되고 해당 속성이 속성 창에 나타납니다.

비동기 작업을 시작하려면 RunWorkerAsync 메서드를 사용합니다. RunWorkerAsync는 작업자 메서드로 인수를 전달하는 데 사용할 수 있는 선택적 object 매개 변수를 사용합니다. BackgroundWorker 클래스는 DoWork 이벤트를 표시하며, 작업자 스레드는 DoWork 이벤트 처리기를 통해 이 이벤트에 연결됩니다.

DoWork 이벤트 처리기는 DoWorkEventArgs 속성을 포함하는 Argument 매개 변수를 사용합니다. 이 속성은 RunWorkerAsync에서 매개 변수를 받으며 작업자 메서드로 전달될 수 있습니다. 이 작업자 메서드는 DoWork 이벤트 처리기에서 호출됩니다. 다음 예에서는 ComputeFibonacci라는 작업자 메서드에서 결과를 할당하는 방법을 보여줍니다. 이 예제는 방법: 백그라운드 작업을 사용하는 폼 구현에서 찾을 수 있는 더 큰 예제의 일부입니다.

// This event handler is where the actual,
// potentially time-consuming work is done.
void backgroundWorker1_DoWork( Object^ sender, DoWorkEventArgs^ e )
{
   // Get the BackgroundWorker that raised this event.
   BackgroundWorker^ worker = dynamic_cast<BackgroundWorker^>(sender);

   // Assign the result of the computation
   // to the Result property of the DoWorkEventArgs
   // object. This is will be available to the 
   // RunWorkerCompleted eventhandler.
   e->Result = ComputeFibonacci( safe_cast<Int32>(e->Argument), worker, e );
}
// This event handler is where the actual,
// potentially time-consuming work is done.
private void backgroundWorker1_DoWork(object sender,
    DoWorkEventArgs e)
{
    // Get the BackgroundWorker that raised this event.
    BackgroundWorker worker = sender as BackgroundWorker;

    // Assign the result of the computation
    // to the Result property of the DoWorkEventArgs
    // object. This is will be available to the
    // RunWorkerCompleted eventhandler.
    e.Result = ComputeFibonacci((int)e.Argument, worker, e);
}
' This event handler is where the actual work is done.
Private Sub backgroundWorker1_DoWork( _
ByVal sender As Object, _
ByVal e As DoWorkEventArgs) _
Handles backgroundWorker1.DoWork

    ' Get the BackgroundWorker object that raised this event.
    Dim worker As BackgroundWorker = _
        CType(sender, BackgroundWorker)

    ' Assign the result of the computation
    ' to the Result property of the DoWorkEventArgs
    ' object. This is will be available to the 
    ' RunWorkerCompleted eventhandler.
    e.Result = ComputeFibonacci(e.Argument, worker, e)
End Sub

이벤트 처리기 사용에 대한 자세한 내용은 이벤트를 참조하세요.

주의

모든 종류의 다중 스레딩을 사용할 때는 매우 심각하고 복잡한 버그에 잠재적으로 노출됩니다. 다중 스레딩을 사용하는 솔루션을 구현하기 전에 관리되는 스레딩을 구현하는 최선의 방법을 참조하세요.

BackgroundWorker 클래스 사용에 대한 자세한 내용은 방법: 백그라운드에서 작업 실행을 참조하세요.

참고 항목