Reputation: 13620
Im using a gmail class so that my app can send me notification over gmail.
Its done like this:
public static void SendMessage(string message)
{
Notification.message = message;
Thread t = new Thread(new ThreadStart(SendMessageThreaded));
t.Start();
}
and the threaded function look like this:
private static void SendMessageThreaded()
{
try
{
if (Notification.message != "")
RC.Gmail.GmailMessage.SendFromGmail("accname", "accpass", "email", "subject", Notification.message);
Notification.message = "";
}
catch
{ }
}
So after SendMessageThreaded
is run, does it close by itself or do i have to
t.Start()
t.Abort()
or something?
Upvotes: 30
Views: 36100
Reputation: 3727
Yes it will close, but you should but a timeout in order to avoid zombies anyway if the main thread crash while the second thread is waiting for it.
Upvotes: 2
Reputation: 2845
No need, it will return back to the thread pool and wait for other task, if none it will kill itself.
Upvotes: 5
Reputation:
The Abort() method throws an ThreadAbortException that you can handle:
public void SendMessageThreaded()
{
try
{
// thread logic
}
catch (ThreadAbortException tae)
{
// thread was aborted, by t.Abort()
}
catch (Exception ex)
{
// other error
}
}
By using
t.Abort(myObject)
you can "send" any object that helps you to handle the abort handling. You can use ExceptionState property to access that object.
Upvotes: 1
Reputation: 136663
The thread needs to be started once - at which point it will execute the code block assigned to it and exit.
You don't need to explicitly clean up the thread in most cases (unless you want to bail out early for example )
Upvotes: 41
Reputation: 59002
The thread will go out of scope and be available for garbage collection as soon as SendFromGmail
finishes.
So yes, it closes automatically.
Upvotes: 6
Reputation: 6627
Yes , the thread is closed by itself.
That is when all instructions in the method run on the secodn thread have been called.
Upvotes: 8