Should I keep a link to the thread after it starts?

I keep reading code and examples of multi-threaded applications. From time to time I see this snipppp:

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(); } private static void DoSomething() { Console.WriteLine("doing something"); } } 

And it bothers me: should I refer to (foreground) somewhere? After all, it is a local variable inside the Go method. Therefore, once Go completed, the link to the stream must be garbage collected. Maybe, maybe the thread will be gced at runtime?

Will the response change if it is a background thread?

Thanks in advance!

+6
source share
3 answers

A thread is one example of an object whose lifetime is not controlled by the garbage collector. Under the hood, this is an object of the operating system. This is live while the thread is working with code. The Thread class is just a wrapper. Another example is a window, it is live until your code or user closes it. Winforms does not require you to contain a reference to the shell of the Form class. And you usually do not do this:

  Application.Run(new Form1()); 

- boiler plate code, you do not keep a link to an instance of the Form1 class anywhere.

You can always recreate a Thread object from an existing thread. You do this with Thread.CurrentThread. And it does not have to be a thread created using the Thread constructor. It can be used inside threadpool thread. Or a thread that was not started by managed code. The main thread of your program would be a good example of this; it was launched by Windows.

However, losing a link to a stream is not good practice. This means that you cannot verify that it is still working. This means that you cannot stop him when you need to stop him. When a user wants to exit your program, for example.

+4
source

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

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

+2
source

You only need to save the link if you want to use it later. In this case, garbage collection will not start until the stream ends.

The only difference between foreground and background threads is that the foreground thread supports a managed runtime.

This means that a working foreground thread will prevent your application from closing, and a background thread will not.

A source

+2
source

Source: https://habr.com/ru/post/891356/


All Articles