İzlenecek yol: Arka Planda İşlem Çalıştırma

Tamamlanması uzun süren bir işleme sahipseniz ve Kullanıcı arabiriminizdeki gecikmelere yol açmak istemiyorsanız, BackgroundWorker işlemi başka bir iş parçacığında çalıştırmak için sınıfını kullanabilirsiniz.

Bu örnekte kullanılan kodun tüm listesi için bkz. nasıl yapılır: arka planda Işlem çalıştırma.

Arka planda işlem çalıştırma

  1. formunuz Visual Studio Windows Form Tasarımcısı etkin olarak, Button araç kutusu 'ndaki iki denetimi forma sürükleyin ve sonra Name Text düğmelerin ve özelliklerini aşağıdaki tabloya göre ayarlayın.

    Düğme Name Metin
    button1 startBtn Başlangıç
    button2 cancelBtn İptal
  2. Araç kutusunu açın, Bileşenler sekmesine tıklayın ve sonra BackgroundWorker bileşen formunuza sürükleyin.

    backgroundWorker1Bileşen, bileşen tepsisinde görünür.

  3. Özellikler penceresinde, WorkerSupportsCancellation özelliğini olarak ayarlayın true .

  4. Özellikler penceresinde, Olaylar düğmesine tıklayın ve ardından DoWork RunWorkerCompleted olay işleyicileri oluşturmak için ve olaylarına çift tıklayın.

  5. Zaman alan kodunuzu DoWork olay işleyicisine ekleyin.

  6. İşlemin gerektirdiği tüm parametreleri Argument parametre özelliğinden ayıklayın DoWorkEventArgs .

  7. Hesaplama sonucunu Result öğesinin özelliğine atayın DoWorkEventArgs .

    Bu, olay işleyicisi tarafından kullanılabilir olacaktır RunWorkerCompleted .

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        // Do not access the form's BackgroundWorker reference directly.
        // Instead, use the reference provided by the sender parameter.
        BackgroundWorker bw = sender as BackgroundWorker;
    
        // Extract the argument.
        int arg = (int)e.Argument;
    
        // Start the time-consuming operation.
        e.Result = TimeConsumingOperation(bw, arg);
    
        // If the operation was canceled by the user,
        // set the DoWorkEventArgs.Cancel property to true.
        if (bw.CancellationPending)
        {
            e.Cancel = true;
        }
    }
    
    Private Sub backgroundWorker1_DoWork( _
    sender As Object, e As DoWorkEventArgs) _
    Handles backgroundWorker1.DoWork
    
       ' Do not access the form's BackgroundWorker reference directly.
       ' Instead, use the reference provided by the sender parameter.
       Dim bw As BackgroundWorker = CType( sender, BackgroundWorker )
       
       ' Extract the argument.
       Dim arg As Integer = Fix(e.Argument)
       
       ' Start the time-consuming operation.
       e.Result = TimeConsumingOperation(bw, arg)
       
       ' If the operation was canceled by the user, 
       ' set the DoWorkEventArgs.Cancel property to true.
       If bw.CancellationPending Then
          e.Cancel = True
       End If
    
    End Sub   
    
  8. Olay işleyicisindeki işlemin sonucunu almak için kod ekleyin RunWorkerCompleted .

    // This event handler demonstrates how to interpret
    // the outcome of the asynchronous operation implemented
    // in the DoWork event handler.
    private void backgroundWorker1_RunWorkerCompleted(
        object sender,
        RunWorkerCompletedEventArgs e)
    {
        if (e.Cancelled)
        {
            // The user canceled the operation.
            MessageBox.Show("Operation was canceled");
        }
        else if (e.Error != null)
        {
            // There was an error during the operation.
            string msg = String.Format("An error occurred: {0}", e.Error.Message);
            MessageBox.Show(msg);
        }
        else
        {
            // The operation completed normally.
            string msg = String.Format("Result = {0}", e.Result);
            MessageBox.Show(msg);
        }
    }
    
    ' This event handler demonstrates how to interpret 
    ' the outcome of the asynchronous operation implemented
    ' in the DoWork event handler.
    Private Sub backgroundWorker1_RunWorkerCompleted( _
    sender As Object, e As RunWorkerCompletedEventArgs) _
    Handles backgroundWorker1.RunWorkerCompleted
    
       If e.Cancelled Then
          ' The user canceled the operation.
          MessageBox.Show("Operation was canceled")
       ElseIf (e.Error IsNot Nothing) Then
          ' There was an error during the operation.
          Dim msg As String = String.Format("An error occurred: {0}", e.Error.Message)
          MessageBox.Show(msg)
       Else
          ' The operation completed normally.
          Dim msg As String = String.Format("Result = {0}", e.Result)
          MessageBox.Show(msg)
       End If
    End Sub   
    
  9. Yöntemini uygulayın TimeConsumingOperation .

    // This method models an operation that may take a long time
    // to run. It can be cancelled, it can raise an exception,
    // or it can exit normally and return a result. These outcomes
    // are chosen randomly.
    private int TimeConsumingOperation(
        BackgroundWorker bw,
        int sleepPeriod )
    {
        int result = 0;
    
        Random rand = new Random();
    
        while (!bw.CancellationPending)
        {
            bool exit = false;
    
            switch (rand.Next(3))
            {
                // Raise an exception.
                case 0:
                {
                    throw new Exception("An error condition occurred.");
                    break;
                }
    
                // Sleep for the number of milliseconds
                // specified by the sleepPeriod parameter.
                case 1:
                {
                    Thread.Sleep(sleepPeriod);
                    break;
                }
    
                // Exit and return normally.
                case 2:
                {
                    result = 23;
                    exit = true;
                    break;
                }
    
                default:
                {
                    break;
                }
            }
    
            if( exit )
            {
                break;
            }
        }
    
        return result;
    }
    
    ' This method models an operation that may take a long time 
    ' to run. It can be cancelled, it can raise an exception,
    ' or it can exit normally and return a result. These outcomes
    ' are chosen randomly.
    Private Function TimeConsumingOperation( _
    bw As BackgroundWorker, _
    sleepPeriod As Integer) As Integer
    
       Dim result As Integer = 0
       
       Dim rand As New Random()
       
         While Not bw.CancellationPending
             Dim [exit] As Boolean = False
    
             Select Case rand.Next(3)
                 ' Raise an exception.
                 Case 0
                     Throw New Exception("An error condition occurred.")
                     Exit While
    
                     ' Sleep for the number of milliseconds
                     ' specified by the sleepPeriod parameter.
                 Case 1
                     Thread.Sleep(sleepPeriod)
                     Exit While
    
                     ' Exit and return normally.
                 Case 2
                     result = 23
                     [exit] = True
                     Exit While
    
                 Case Else
                     Exit While
             End Select
    
             If [exit] Then
                 Exit While
             End If
         End While
       
       Return result
    End Function
    
  10. Windows Form Tasarımcısı startButton olay işleyicisini oluşturmak için çift tıklayın Click .

  11. RunWorkerAsync Click İçin olay işleyicisinde yöntemi çağırın startButton .

    private void startBtn_Click(object sender, EventArgs e)
    {
        this.backgroundWorker1.RunWorkerAsync(2000);
    }
    
    Private Sub startButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles startBtn.Click
        Me.backgroundWorker1.RunWorkerAsync(2000)
    End Sub
    
  12. Windows Form Tasarımcısı cancelButton olay işleyicisini oluşturmak için çift tıklayın Click .

  13. CancelAsync Click İçin olay işleyicisinde yöntemi çağırın cancelButton .

    private void cancelBtn_Click(object sender, EventArgs e)
    {
        this.backgroundWorker1.CancelAsync();
    }
    
    Private Sub cancelButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cancelBtn.Click
        Me.backgroundWorker1.CancelAsync()
    End Sub
    
  14. Dosyanın en üstünde System. ComponentModel ve System. Threading ad alanlarını içeri aktarın.

    using System;
    using System.ComponentModel;
    using System.Drawing;
    using System.Threading;
    using System.Windows.Forms;
    
    Imports System.ComponentModel
    Imports System.Drawing
    Imports System.Threading
    Imports System.Windows.Forms
    
  15. Çözümü derlemek için F6 tuşuna basın ve ardından + uygulamayı hata ayıklayıcı dışında çalıştırmak için CTRL F5 tuşuna basın.

    Not

    Uygulamayı hata ayıklayıcı altında çalıştırmak için F5 tuşuna basarsanız, yöntemde oluşturulan özel durum TimeConsumingOperation hata ayıklayıcı tarafından yakalanır ve görüntülenir. Uygulamayı hata ayıklayıcı dışında çalıştırdığınızda, BackgroundWorker özel durumu işler ve Error öğesinin özelliğinde önbelleğe alır RunWorkerCompletedEventArgs .

  16. Zaman uyumsuz bir işlem çalıştırmak için Başlat düğmesine tıklayın ve ardından çalışan bir zaman uyumsuz işlemi durdurmak için iptal düğmesine tıklayın.

    Her işlemin sonucu bir içinde görüntülenir MessageBox .

Sonraki adımlar

Ayrıca bkz.