user2949159
user2949159

Reputation: 31

sleeping in background thread freezes UI thread

I have a background worker to check the email queue and if there are items in the queue, send the emails. If there are no items, the background thread sleeps for five seconds and then checks the queue again for items. For whatever reason, the UI thread is also freezing. Why would the sleeping in the background thread affect the UI thread?

Here is the code:

// global variables
    private BackgroundWorker emailBackgroundWorker = null;
    private EmailQueue emailQueue = null;

// load WPF window
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {

        emailBackgroundWorker = startEmailBackgroundWorker();

}   

    private BackgroundWorker startEmailBackgroundWorker()
    {
        exceptionLogger.Info("Starting email queue");
        emailQueue = new EmailQueue();

        BackgroundWorker worker = new BackgroundWorker();
        worker.DoWork += new DoWorkEventHandler(EmailBackgroundWorker_Handler);
        worker.RunWorkerAsync();
        return worker;
    }

    private void EmailBackgroundWorker_Handler(object source, DoWorkEventArgs args)
    {
        if (emailQueue.Count() > 0)
        {
            // send email
            EmailItem emailItem = emailQueue.Dequeue();
            if (emailItem != null)
            {
                // process email
                exceptionLogger.Info("Sending email from email queue");
                EmailNotify emailNotify = new EmailNotify(exceptionLogger);
                emailNotify.send(emailItem.BeltGardEmail, smtpData, emailItem.EmailList, emailItem.Message, emailItem.PdfAttachment, emailItem.PdfFileName, false);
            }
        }
        else
        {
            System.Threading.Thread.Sleep(5000);  // sleep five seconds
        }
        return;
    }

Upvotes: 0

Views: 53

Answers (0)

Related Questions