Search code examples
vb.netvisiblethread-sleep

Using Sleep in VB.NET


I have a kind of simple issue, I have a section of code that sends out a test email and just before this process occurs, I'd like a marquee progress bar to appear, indicating that something is happening.

However, the progress bar does not appear until the test email has been sent.

I've tried experimenting with the Sleep function, but the progress bar still wont appear until after the test email sends.

Does anyone know why?

Code: (Note: GroupBoxTesting contains the Progress bar)

 Private Sub BTMsendmailtest_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTMsendmailtest.Click

        GroupBoxTesting.Visible = True

        Threading.Thread.Sleep(500)

        Try
            Dim Mail As New MailMessage

            Mail.Subject = "Test email for Email Alerts!"
            Mail.To.Add(TXTemailaddy.Text)

            Mail.From = New MailAddress(TXTsmtpusr.Text)
            Mail.Body = "This is a test message from Email Alerts!" & Environment.NewLine & Environment.NewLine & "If you are reading this, then Email Alerts! is properly configured."

            Dim SMTP As New SmtpClient(TXTsmtpsvr.Text)
            If CHKEnableSSL.Checked = True Then
                SMTP.EnableSsl = True
            Else
                SMTP.EnableSsl = False
            End If
            SMTP.Credentials = New System.Net.NetworkCredential(TXTsmtpusr.Text, TXTsmtppwd.Text)
            SMTP.Port = TXTsmtpport.Text
            SMTP.Send(Mail)
            SendingPB.Value = False
            MessageBox.Show("A test email has been sent to " & TXTemailaddy.Text & " from " & TXTsmtpusr.Text & "." & Environment.NewLine & Environment.NewLine & "If you did not recieve an email, please check your settings and try again.", "Test Email")
            GroupBoxTesting.Visible = False
        Catch ex1 As Exception
            SendingPB.Value = False
            GroupBoxTesting.Visible = False
            MessageBox.Show(ex1.Message)
            Return
        End Try
    End Sub

Solution

  • You've told the UI thread (which is the thread your code as it is is currently running on) to go to sleep, so it goes to sleep and doesn't do anything for the specified time. Even without the Sleep, it may be that the UI thread is too busy sending the email to update the display of the marquee progress bar.

    You could either use a BackgroundWorker to send the email, or use the SmtpClient.SendAsync Method. The latter includes an example; there is another example at How do I send email asynchronously?.