46

I have the following code:

        public static void Send(this MailMessage email)
    {
        if (!isInitialized)
            Initialize(false);
        //smtpClient.SendAsync(email, "");
        email.IsBodyHtml = true;

        Thread mailThread = new Thread(new ParameterizedThreadStart(
            (o) => 
            {
                var m = o as MailMessage;

                SmtpClient client= new SmtpClient("smtpserveraddress");
                client.Send(m);

            }));
        mailThread.Start(email);

I want the mail sending to be done in the background without interfering with the main thread. I do not care when it is finished.

Do I need to somehow handle the dispose of the created thread (mailThread)? Or does it automatically dispose when it finishes its job?

Please do not recommend the SendAsync method. I would like to create the thread manually. Mail.Send was only an example scenario.

Thank you.

Aaron Azhari
  • 987
  • 1
  • 10
  • 24

3 Answers3

69

NO!

there is no need to dispose the Thread object (BTW, the Thread class does not provide the Dispose method).

platon
  • 5,310
  • 1
  • 22
  • 24
14

Thread is diposed when its routine comes at end.
So NO, you don't have to do it, it's not necessary (nor possible I think).

Marco
  • 56,740
  • 14
  • 129
  • 152
  • 7
    But not the thread object. The thread object is eligible for garbage collection immediately. http://stackoverflow.com/questions/3699147/c-sharp-thread-object-lifetime – Jirka Hanika May 22 '12 at 08:13
1

Well, your SmtpClient should be Dispose()'d. I'd use the Task Parallel Library instead of creating raw threads:

public static void Send(this MailMessage email)
{
    if (!isInitialized)
        Initialize(false);
    //smtpClient.SendAsync(email, "");
    email.IsBodyHtml = true;

    Task.Factory.StartNew(() =>
    {
        // Make sure your caller Dispose()'s the email it passes in at some point!
        using (SmtpClient client = new SmtpClient("smtpserveraddress"))
        {
            client.Send(email);
        }
    });
}
Jesse C. Slicer
  • 19,901
  • 3
  • 68
  • 87
  • 1
    As a side note, if someone decides to call this method in an ASP.Net application, the Thread used to make this call will be one from the application pool, and with enough of these types of calls can technically starve the IIS thread pool. Creating a new thread `new Thread` does not have this issue (although does create new overhead in creating the thread). – Erik Philips Nov 18 '14 at 21:22
  • You should always await on tasks. See my question at http://stackoverflow.com/questions/14346108/what-happens-to-work-scheduled-by-task-run-after-the-the-program-terminates – Bruno Brant Nov 03 '16 at 16:23