Topic Creation Area and Garbage Collector

It doesn’t matter for the garbage collector if we declare the stream in the method scope and not in the class scope, for example:

//scenario 1 public class Foo { public Foo() { new Thread(()=> /*engine*/) { IsBackground = true }.Start(); } } //scenario 2 public class Bar { private readonly Thread _engineThread = null; public Bar() { _engineThread = new Thread(()=> /*engine*/) { IsBackground = true }; _engineThread.Start(); } } 
+3
source share
1 answer

Yes - in the first approach, the Thread object will have the right to garbage collection as soon as the main thread is completed.

In the second approach, if the Bar instance is still not suitable for garbage collection, this will prevent the collection of the Thread object. I doubt that this will affect the main OS thread, mind you.

I would not have thought about the implications of GC, although I would have focused on readability. For some reason, do you need a link to this background thread? If so, move on to the second approach so that it is available to you. If you do not need it, it would be pointless to have it as a field.

+5
source

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


All Articles