Does it make any difference for the garbage coll开发者_开发技巧ector if we declare a thread at method scope rather than at class scope, like:
//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();
}
}
Yes - in the first approach, the Thread
object will be eligible for garbage collection as soon as the underlying thread has completed.
In the second approach, if the instance of Bar
is still not eligible for garbage collection, that will prevent the Thread
object from being garbage collected. I doubt that that will have any impact on the underlying OS thread, mind you.
I wouldn't think about the GC implications though - I'd concentrate on readability. Do you need a reference to that background thread for some reason? If so, go with the second approach so that it's available to you. If you don't need it, it would be pointless having it as a field.
精彩评论