Пример. Фоновое выполнение операции
Если какая-либо операция будет выполняться в течение долгого времени и при этом требуется не допустить задержек в работе пользовательского интерфейса, можно использовать класс BackgroundWorker для выполнения операции в другом потоке.
Полный листинг кода, используемого в этом примере, см. в разделе Практическое руководство. Фоновое выполнение операции.
Фоновое выполнение операции
Активируйте вашу форму в конструкторе Windows Forms в Visual Studio, перетащите два элемента управления Button из панели элементов в форму, а затем задайте свойства
Name
и Text кнопок в соответствии со следующей таблицей.Button Имя Текст button1
startBtn
Начало button2
cancelBtn
Cancel Откройте панель элементов, щелкните вкладку Компоненты, а затем перетащите из нее компонент BackgroundWorker в вашу форму.
Компонент
backgroundWorker1
отображается в области компонентов.В окне Свойства присвойте свойству WorkerSupportsCancellation значение
true
.В окне Свойства нажмите кнопку События, а затем дважды щелкните события DoWork и RunWorkerCompleted, чтобы создать обработчики событий.
Вставьте ваш требующий времени код в обработчик событий DoWork.
Извлеките все параметры, необходимые для операции, из свойства Argument параметра DoWorkEventArgs.
Назначьте результат вычисления свойству ResultDoWorkEventArgs.
Этот результат будет доступен обработчику событий 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
Вставьте код для получения результата операции в обработчик событий 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
Реализуйте метод
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
В конструкторе Windows Forms дважды щелкните
startButton
, чтобы создать обработчик события Click.Вызовите метод RunWorkerAsync в обработчике событий Click для
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
В конструкторе Windows Forms дважды щелкните
cancelButton
, чтобы создать обработчик события Click.Вызовите метод CancelAsync в обработчике событий Click для
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
В верхней части файла импортируйте пространства имен 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
Нажмите клавишу F6, чтобы выполнить сборку решения, а затем нажмите сочетание клавиш CTRL+F5, чтобы запустить приложение не в отладчике.
Примечание.
Если нажать клавишу F5 для запуска приложения в отладчике, то исключение, возникающее в методе
TimeConsumingOperation
, будет перехвачено и отображено отладчиком. При запуске приложения не в отладчике BackgroundWorker будет обрабатывать исключение и кэшировать его в свойстве ErrorRunWorkerCompletedEventArgs.Нажмите кнопку Запуск, чтобы запустить асинхронную операцию, а затем нажмите кнопку Отмена, чтобы остановить выполнение асинхронной операции.
Результат каждой операции выводится в элементе MessageBox.
Следующие шаги
Реализация формы, которая сообщает о ходе выполнения по мере продолжения асинхронной операции. Дополнительные сведения см. в разделе Практическое руководство. Реализация формы, в которой выполняется фоновая операция.
Реализация класса, поддерживающего асинхронную модель для компонентов. Дополнительные сведения см. в разделе Реализация асинхронной модели, основанной на событиях.
См. также
.NET Desktop feedback