Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need to dispose or terminate a thread in C# after usage?

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.

like image 334
Aaron Azhari Avatar asked May 22 '12 08:05

Aaron Azhari


People also ask

How do you dispose of threads?

As you tend to your garden, remember plant pots do not go in the recycling bin. Reuse them or take them to these drop-off locations. 100% cotton yarn or thread can be composted. All other yarn or thread goes in the trash if it can't be reused.

Is dispose thread safe?

Most disposable objects are not thread-safe. After all, calling Dispose on one thread while other threads are accessing the object is bound to cause problems.

What is thread abort?

Abort(Object) Obsolete. Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread while also providing exception information about the thread termination. Calling this method usually terminates the thread.


1 Answers

NO!

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

like image 64
platon Avatar answered Sep 18 '22 13:09

platon