您好再次StackOverflow社區!VB.Net BackgroundWorker和AsyncCancel無法正常工作
我遇到了BackgroundWorker和AsyncCancel的一些問題。 BackgroundWorker只發送一封電子郵件,但我希望能夠報告何時發送任務或電子郵件,並且能夠取消發送的任務或電子郵件。
問題是點擊取消後,它繼續,然後報告錯誤,沒有取消。
任何幫助,非常感謝!
謝謝!
這裏是我完整的代碼減去意見和進口:
Private Sub Sendmail_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
StatusLabel.Text &= "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("[email protected]", "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!" & vbNewLine & vbNewLine & 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 &= "Worker Error!" & vbNewLine & vbNewLine & e.Error.Message
ElseIf e.Cancelled Then
StatusLabel.Text &= "Canceled!"
Else
StatusLabel.Text &= "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 &= "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
您擁有的另一個問題是發送郵件可能非常快。這可能是用戶甚至沒有時間取消發送。 – Enigmativity