逐步解說:在背景執行作業

如果您有要花費較長時間才能完成的作業,但您不想導致使用者介面發生延遲,就可以使用 BackgroundWorker 類別在另一個執行緒上執行該作業。

如需此範例中使用的程式碼完整清單,請參閱操作說明:在背景執行作業

在背景執行作業

  1. 在 Visual Studio 的 Windows Form 設計工具中,將兩個 Button 控制項從 [工具箱] 拖曳至表單,然後根據下表設定按鈕的 NameText 屬性。

    按鈕 名稱 Text
    button1 startBtn 啟動
    button2 cancelBtn 取消
  2. 開啟 [工具箱],按一下 [元件] 索引標籤,然後將 BackgroundWorker 元件拖曳到表單上。

    backgroundWorker1 元件會出現在 [元件匣] 中。

  3. 在 [屬性] 視窗中,將 WorkerSupportsCancellation 屬性設定為 true

  4. 在 [屬性] 視窗中,按一下 [事件] 按鈕,然後按一下 DoWorkRunWorkerCompleted 事件來建立事件處理常式。

  5. 將耗時的程式碼插入 DoWork 事件處理常式中。

  6. DoWorkEventArgs 參數的 Argument 屬性擷取作業所需的任何參數。

  7. 將計算的結果指派給 DoWorkEventArgsResult 屬性。

    這可供 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. 插入程式碼,以在 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. 實作 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 設計工具中,按一下 startButton 以建立 Click 事件處理常式。

  11. startButtonClick 事件處理常式中呼叫 RunWorkerAsync 方法。

    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 設計工具中,按一下 cancelButton 以建立 Click 事件處理常式。

  13. cancelButtonClick 事件處理常式中呼叫 CancelAsync 方法。

    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. 在檔案頂端,匯入 System.ComponentModel 和 System.Threading 命名空間。

    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. F6 建置方案,然後按 Ctrl+F5 以在偵錯工具外部執行應用程式。

    注意

    如果您按下 F5 以在偵錯工具下執行應用程式,偵錯工具就會攔截 TimeConsumingOperation 方法中引發的例外狀況並加以顯示。 當您在偵錯工具外部執行應用程式時,BackgroundWorker 會處理例外狀況,並將其快取在 RunWorkerCompletedEventArgsError 屬性中。

  16. 按一下 [開始] 按鈕以執行非同步作業,然後按一下 [取消] 按鈕以停止執行中的非同步作業。

    每個作業的結果會顯示於 MessageBox

下一步

另請參閱