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?

Answers


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 )


Yes , the thread is closed by itself.

That is when all instructions in the method run on the secodn thread have been called.


The thread will go out of scope and be available for garbage collection as soon as SendFromGmail finishes.

So yes, it closes automatically.


No need, it will return back to the thread pool and wait for other task, if none it will kill itself.


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


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.


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.


Need Your Help

How do I know if a process is creating IO blocking?

windows performance windows-server-2012 windows-server windows-server-2012-r2

I'm trying to get the max possible performance out of a Java software we are building, but currently I'm facing an issue where server's resources don't seem to be exhausted and the app doesn't go any

Tire gem: How to access Elasticsearch's 'highlight' property?

ruby-on-rails ruby-on-rails-3 elasticsearch tire

I have some Rails models that are indexed in Elasticsearch (via Tire gem). I can index new documents and query the existing index.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.