Imports System.ComponentModel

Public Class Form1

    Public Sub New()

        InitializeComponent()

        BackgroundWorker1.WorkerReportsProgress = True
        BackgroundWorker1.WorkerSupportsCancellation = True

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If BackgroundWorker1.IsBusy <> True Then
            ProgressBar1.Value = 0
            BackgroundWorker1.RunWorkerAsync()
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If BackgroundWorker1.WorkerSupportsCancellation = True Then
            BackgroundWorker1.CancelAsync()
        End If
    End Sub

    Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        Dim work As BackgroundWorker = CType(sender, BackgroundWorker)
        Dim i As Integer
        For i = 1 To 10
            If work.CancellationPending = True Then
                e.Cancel = True
                Exit For
            Else
                System.Threading.Thread.Sleep(500)
                work.ReportProgress(i * 10)

            End If
        Next

    End Sub

    Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
        Label1.Text = e.ProgressPercentage.ToString & "%"
        ProgressBar1.Value = ProgressBar1.Value + 10
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        If e.Cancelled = True Then
            Label1.Text = "انصراف"
        ElseIf e.Error IsNot Nothing Then
            Label1.Text = "خطا"
        Else
            Label1.Text = "پایان"
        End If
    End Sub
End Class
