こんにちは、もう一度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