I'm developing an application where a user clicks/presses enter on a certain button in a window, the application does some checks and determines whether to send out a couple of emails or not, then show another window with a message.
My issue is, sending out the 2 emails slows the process noticeably, and for some (~8) seconds the first window looks frozen while it's doing the sending.
Is there any way I can have these emails sent on the background and display the next window right away?
Please don't limit your answer with "use X class" or "just use X method" as I am not all too familiarized with the language yet and some more information would be highly appreciated.
Thanks.
Here is a fire and forget approach together with async using .Net 4.5.2+:
where BackgroundTaskRunner is:
Works like a charm on Azure App Services.
As it's a small unit of work you should use ThreadPool.QueueUserWorkItem for the threading aspect of it. If you use the SmtpClient class to send your mail you could handle the SendCompleted event to give feedback to the user.
By creating a fresh SMTP client each time this will allow you to send out emails simultaneously.
Try this:
The easiest Solution is to create a BackgroundWorker and push the mails into a queue. Then just let the BackgroundWorker go through the queue and send each mail.
See also How to: Run an Operation in the Background
Use the SmtpClient class and use the method SendAsync in the System.Net.Mail namespace.
What you want to do is run the e-mail task on a separate thread so the main code can continue processing while the other thread does the e-mail work.
Here is a tutorial on how to do that: Threading Tutorial C#