开发者

Should I hold a reference to a thread once its started?

I keep reading code and examples of multi-threaded applications. From time to time I see a snippet like so:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("started");
        Go();
        Console.WriteLine("press [ENTER] to quit");
        Console.ReadLine();
    }

    private static void Go()
    {
        var thread = new Thread(DoSomething);
        thread.Start();
    }开发者_如何学JAVA

    private static void DoSomething()
    {
        Console.WriteLine("doing something");
    }
}

And it keeps bothering me: should I keep the reference to the (foreground) thread somewhere? After all, it's a local variable inside Go method. Hence, once the execution of Go is completed, the thread reference should be garbage-collected. So maybe, just maybe, the thread will be GCed while it's executing?

Will the answer change if it's a background thread?

Thanks in advance!


A thread is one example of an object whose lifetime is not controlled by the garbage collector. Under the hood it is an operating system object. That's alive as long as a thread is running code. The Thread class is just a wrapper for it. Another example is a window, it is alive as long as your code or the user doesn't close it. Winforms doesn't require that you hold a reference to the Form class wrapper. And you very typically don't:

 Application.Run(new Form1());

is the boiler plate code, you don't hold a reference to the Form1 class instance anywhere.

You can always re-create a Thread object from an existing running thread. You do so with Thread.CurrentThread. And it doesn't have to be a thread that you created with the Thread constructor. It can be used inside a threadpool thread. Or a thread that wasn't started by managed code. The main thread of your program would be a good example of that, it was started by Windows.

Nevertheless, losing a reference to a thread is not good practice. It implies that you can't check that it is still running. Which implies that you cannot stop it when it should be stopped. When the user wants to quit your program for example.


According to this answer, you have nothing to worry about. The GC is smart enough to know if a thread is being used.

Here is an article explaining the behavior: http://msdn.microsoft.com/en-us/magazine/bb985011.aspx#ctl00_MTContentSelector1_mainContentContainer_ctl03


You only need to keep hold of the reference if you want to use it later. In this case the garbage collection won't kick in until the thread has finished.

The only difference between foreground and background threads is that a foreground thread keeps the managed execution environment running.

This means that a running foreground thread will prevent your application closing, while a background one won't.

Source

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜