VB.Net BackgroundWorker and AsyncCancel Not Working Correctly
<p>Hello again StackOverflow Community!</p>

<p>I am having some issues with a BackgroundWorker and AsyncCancel. The BackgroundWorker simply sends a email but I would like to be able to report when the task or email has been sent and as well be able to cancel the task or email from being sent.</p>

<p>The problem is after hitting cancel, it continues and then reports a error, not canceled.</p>

<p>Any help is greatly appreciated!</p>

<p>Thank you!</p>

<p>Here is my complete code minus comments and imports:</p>

<pre><code>Private Sub Sendmail_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    StatusLabel.Text &amp;= "Idle"

End Sub

Private Sub SendmailBackgroundWorker_DoWork(sender As Object, e As DoWorkEventArgs) Handles SendmailBackgroundWorker.DoWork

    Try

        Dim Smtp As New SmtpClient()
        Dim Email As New MailMessage()

        Smtp.Port = 25
        Smtp.Host = "mail.server.com"

        Smtp.EnableSsl = False
        Smtp.UseDefaultCredentials = False

        Smtp.Credentials = New Net.NetworkCredential("user@server.com", "password")

        Email = New MailMessage()
        Email.From = New MailAddress(FromTextBox.Text)
        Email.To.Add(ToTextBox.Text)
        Email.Subject = SubjectTextBox.Text
        Email.IsBodyHtml = False
        Email.Body = BodyTextBox.Text

        Smtp.Send(Email)

    Catch ex As Exception

        MsgBox("Sendmail Error!" &amp; vbNewLine &amp; vbNewLine &amp; ex.ToString)

    End Try

    If SendmailBackgroundWorker.CancellationPending Then

        StatusLabel.Text = "Canceling"
        e.Cancel = True

    End If

End Sub

Private Sub SendmailBackgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles SendmailBackgroundWorker.RunWorkerCompleted

    StatusLabel.Text = "Status: "

    If (e.Error IsNot Nothing) Then


        StatusLabel.Text &amp;= "Worker Error!" &amp; vbNewLine &amp; vbNewLine &amp; e.Error.Message

    ElseIf e.Cancelled Then

        StatusLabel.Text &amp;= "Canceled!"

    Else

        StatusLabel.Text &amp;= "Sent!"

    End If

    SendButton.Enabled = True
    CancelButton.Enabled = False

End Sub

Private Sub SendButton_Click(sender As Object, e As EventArgs) Handles SendButton.Click

    StatusLabel.Text = "Status: "

    SendButton.Enabled = False
    CancelButton.Enabled = True

    SendmailBackgroundWorker.WorkerSupportsCancellation = True
    SendmailBackgroundWorker.WorkerReportsProgress = True

    StatusLabel.Text &amp;= "Sending..."

    SendmailBackgroundWorker.RunWorkerAsync()

End Sub

Private Sub CancelButton_Click(sender As Object, e As EventArgs) Handles CancelButton.Click

    CancelButton.Enabled = False
    SendmailBackgroundWorker.CancelAsync()

End Sub
</code></pre>