방법: 이벤트 기반 비동기 패턴을 지원하는 구성 요소 사용

많은 구성 요소가 비동기적으로 작업을 수행하는 옵션을 제공합니다. 예를 들어 SoundPlayerPictureBox 구성 요소를 사용하면 기본 스레드가 중단 없이 계속 실행되는 동안 사운드 및 이미지를 “배경”으로 로드할 수 있습니다.

이벤트 기반 비동기 패턴 개요를 지원하는 클래스에 비동기 메서드를 사용하는 작업은 다른 이벤트의 경우와 같이 구성 요소의 MethodNameCompleted 이벤트에 이벤트 처리기를 연결하는 것처럼 간단할 수 있습니다. MethodNameAsync 메서드를 호출하면 애플리케이션은 MethodNameCompleted 이벤트가 발생할 때까지 중단 없이 계속 실행됩니다. 이벤트 처리기에서 AsyncCompletedEventArgs 매개 변수를 검사하여 비동기 작업이 성공적으로 완료되었는지 또는 취소되었는지 확인할 수 있습니다.

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

다음 절차는 PictureBox 컨트롤의 비동기 이미지 로드 기능을 사용하는 방법을 보여줍니다.

PictureBox 컨트롤을 사용하여 이미지를 비동기적으로 로드하게 하려면

  1. 폼에서 PictureBox 구성 요소의 인스턴스를 만듭니다.

  2. 이벤트 처리기를 LoadCompleted 이벤트에 할당합니다.

    여기에서 비동기 다운로드 중에 발생했을 수 있는 오류를 확인합니다. 여기에서 취소를 확인할 수도 있습니다.

    public Form1()
    {
        InitializeComponent();
    
        this.pictureBox1.LoadCompleted +=
            new System.ComponentModel.AsyncCompletedEventHandler(this.pictureBox1_LoadCompleted);
    }
    
    Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox
    
    private void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            MessageBox.Show(e.Error.Message, "Load Error");
        }
        else if (e.Cancelled)
        {
            MessageBox.Show("Load canceled", "Canceled");
        }
        else
        {
            MessageBox.Show("Load completed", "Completed");
        }
    }
    
    Private Sub PictureBox1_LoadCompleted( _
        ByVal sender As System.Object, _
        ByVal e As System.ComponentModel.AsyncCompletedEventArgs) _
        Handles PictureBox1.LoadCompleted
    
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message, "Load Error")
        ElseIf e.Cancelled Then
            MessageBox.Show("Load cancelled", "Canceled")
        Else
            MessageBox.Show("Load completed", "Completed")
        End If
    
    End Sub
    
  3. loadButtoncancelLoadButton이라는 두 개의 단추를 폼에 추가합니다. Click 이벤트 처리기를 추가하여 다운로드를 시작 및 취소합니다.

    private void loadButton_Click(object sender, EventArgs e)
    {
        // Replace with a real url.
        pictureBox1.LoadAsync("https://unsplash.com/photos/qhixfmpqN8s/download?force=true&w=1920");
    }
    
    Private Sub loadButton_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles loadButton.Click
    
        ' Replace with a real url.
        PictureBox1.LoadAsync("https://unsplash.com/photos/qhixfmpqN8s/download?force=true&w=1920")
    
    End Sub
    
    private void cancelLoadButton_Click(object sender, EventArgs e)
    {
        pictureBox1.CancelAsync();
    }
    
    Private Sub cancelLoadButton_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles cancelLoadButton.Click
    
        PictureBox1.CancelAsync()
    
    End Sub
    
  4. 애플리케이션을 실행합니다.

    이미지 다운로드가 진행되면 폼을 자유롭게 이동하고, 최소화하고, 최대화할 수 있습니다.

참고 항목