0

我有这个代码:

For i = 0 To DataGridView1.RowCount - 2
    If send_email(body, DataGridView1.Rows(i).Cells(8).Value.ToString) Then
        countSentMail = countSentMail + 1
        System.Threading.Thread.Sleep(2 * 1000)
        ProgressBar1.PerformStep()
    End If
Next i

Private Function send_email(ByVal body As String, ByVal emailAddress As String) As Boolean
    Try
        Dim SmtpServer As New SmtpClient()
        Dim mail As New MailMessage()
        SmtpServer.Port = [port]
        SmtpServer.Host = [ip]
        mail = New MailMessage()
        mail.From = New MailAddress([email_from])
        mail.To.Add([email_to])
        mail.Bcc.Add([email_bbc])
        mail.Subject = [subject]
        mail.Body = body
        Mail.IsBodyHtml = True
        SmtpServer.Send(mail)
        send_email = True
    Catch ex As Exception
        send_email = False
    End Try
End Function

当代码运行时,表单/应用程序会“无响应”,直到发送所有电子邮件并且进度条变得无用。如果我注释掉发送功能的内容 - 进度条按我的预期工作。有什么建议么?

4

1 回答 1

1

很抱歉延迟回复。

是的。您send_email在增加之前调用ProgressBar1

send_email使用SmtpClient.Send()它是同步的并等待服务器响应。

您可以SmtpClient.SendAsync()改用,它将继续执行并在后台等待服务器响应。

于 2013-12-19T10:55:19.560 回答