İzlenecek yol: Arka Planda İşlem Çalıştırma
Tamamlanması uzun sürecek bir işleminiz varsa ve kullanıcı arabiriminizde gecikmelere neden olmak istemiyorsanız, işlemi başka bir iş parçacığında çalıştırmak için sınıfını kullanabilirsiniz BackgroundWorker .
Bu örnekte kullanılan kodun tam listesi için bkz . Nasıl yapılır: Arka Planda İşlem Çalıştırma.
Arka planda işlem çalıştırma
Formunuz Visual Studio'daki Windows Forms Tasarım Aracı etkinken, Araç Kutusu'ndan forma iki Button denetim sürükleyin ve düğmelerin
Name
ve Text özelliklerini aşağıdaki tabloya göre ayarlayın.Düğme Ad Metin button1
startBtn
Başlangıç button2
cancelBtn
İptal Araç Kutusu'nu açın, Bileşenler sekmesine tıklayın ve ardından bileşeni formunuza sürükleyinBackgroundWorker.
Bileşen,
backgroundWorker1
Bileşen Tepsisi'nde görünür.Özellikler penceresinde özelliğini olarak
true
ayarlayınWorkerSupportsCancellation.Özellikler penceresinde Olaylar düğmesine tıklayın ve sonra olay işleyicileri oluşturmak için ve RunWorkerCompleted olaylarına çift tıklayınDoWork.
Zaman alan kodunuzu olay işleyicisine DoWork ekleyin.
parametresinin özelliğinden ArgumentDoWorkEventArgs işlemin gerektirdiği parametreleri ayıklayın.
Hesaplamanın sonucunu özelliğinin Result öğesine atayın DoWorkEventArgs.
Bu, olay işleyicisi RunWorkerCompleted tarafından kullanılabilir.
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
Olay işleyicisinde işleminizin RunWorkerCompleted sonucunu almak için kod ekleyin.
// 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
yöntemini uygulayın.// 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 Tasarım Aracı olay işleyicisini Click oluşturmak için çift tıklayın
startButton
.RunWorkerAsync için
startButton
olay işleyicisinde Click yöntemini çağırın.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 Tasarım Aracı olay işleyicisini Click oluşturmak için çift tıklayın
cancelButton
.CancelAsync için
cancelButton
olay işleyicisinde Click yöntemini çağırın.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
Dosyanın üst kısmında 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
Çözümü oluşturmak için F6 tuşuna basın ve ardından Ctrl+F5 tuşlarına basarak uygulamayı hata ayıklayıcının dışında çalıştırın.
Dekont
Uygulamayı hata ayıklayıcısı altında çalıştırmak için F5 tuşuna basarsanız, yönteminde
TimeConsumingOperation
tetiklenen özel durum yakalanıp hata ayıklayıcı tarafından görüntülenir. Uygulamayı hata ayıklayıcının dışında çalıştırdığınızda BackgroundWorker , özel durumu işler ve özelliğinde ErrorRunWorkerCompletedEventArgsönbelleğe alır.Zaman uyumsuz bir işlemi çalıştırmak için Başlangıç düğmesine tıklayın ve ardından zaman uyumsuz bir işlemi durdurmak için İptal düğmesine tıklayın.
Her işlemin sonucu bir MessageBoxiçinde görüntülenir.
Sonraki adımlar
Zaman uyumsuz bir işlem devam ederken ilerleme durumunu bildiren bir form uygulayın. Daha fazla bilgi için bkz . Nasıl yapılır: Arka Plan İşlemi Kullanan Bir Form Uygulama.
Bileşenler için Zaman Uyumsuz Deseni destekleyen bir sınıf uygulayın. Daha fazla bilgi için bkz . Olay Tabanlı Zaman Uyumsuz Deseni Uygulama.
Ayrıca bkz.
.NET Desktop feedback
Geri Bildirim
https://aka.ms/ContentUserFeedback.
Çok yakında: 2024 boyunca, içerik için geri bildirim mekanizması olarak GitHub Sorunları’nı kullanımdan kaldıracak ve yeni bir geri bildirim sistemiyle değiştireceğiz. Daha fazla bilgi için bkz.Gönderin ve geri bildirimi görüntüleyin