babboon
babboon

Reputation: 793

vb.net while sending smtp form get not responding

I have this code:

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

And when code runs form/application gets "not responding" till sends out all email and progress bar becomes useless. If I comment out content of sending function - progress bar works as I expect. Any suggestions?

Upvotes: 0

Views: 413

Answers (1)

ɐsɹǝʌ ǝɔıʌ
ɐsɹǝʌ ǝɔıʌ

Reputation: 4512

Sorry for the delay on reply.

Yes. You are invoking send_email before increasing ProgressBar1

send_email uses SmtpClient.Send() which is synchronous and waits for a server response.

You can use SmtpClient.SendAsync() instead, which will continue the execution and waits the server response on background.

Upvotes: 1

Related Questions