Backgroundworker
WithEvents
Imports System.ComponentModel Public Class Form1 Private Sub startAsyncButton_Click(sender As Object, e As EventArgs) Handles startAsyncButton.Click Try If BackgroundWorker1.IsBusy <> True Then BackgroundWorker1.RunWorkerAsync() End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub cancelAsyncButton_Click(sender As Object, e As EventArgs) Handles cancelAsyncButton.Click Try If BackgroundWorker1.WorkerSupportsCancellation = True Then BackgroundWorker1.CancelAsync() End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub Public Sub New() InitializeComponent() BackgroundWorker1.WorkerReportsProgress = True BackgroundWorker1.WorkerSupportsCancellation = True End Sub Private Sub backgroundWorker1_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork Try Dim worker As BackgroundWorker = TryCast(sender, BackgroundWorker) For i As Integer = 1 To 100 If worker.CancellationPending = True Then e.Cancel = True Exit For Else System.Threading.Thread.Sleep(100) worker.ReportProgress(i) End If Next Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub backgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged Try resultLabel.Text = (e.ProgressPercentage.ToString() & "%") ProgressBar1.Value = e.ProgressPercentage Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted Try If e.Cancelled = True Then resultLabel.Text = "Canceled!" ElseIf e.[Error] IsNot Nothing Then resultLabel.Text = "Error: " & e.[Error].Message Else resultLabel.Text = "Done!" End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub End Class
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)