Jason94
Jason94

Reputation: 13620

Does a thread close automatically?

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

Answers (7)

ykatchou
ykatchou

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

styshoo
styshoo

Reputation: 681

yes,definitely. it will close itself when it ends.

Upvotes: 7

hallie
hallie

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

user432219
user432219

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

Gishu
Gishu

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

alexn
alexn

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

Liviu Mandras
Liviu Mandras

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

Related Questions