Thread creation scope and the garbage collector

2019-03-31 07:31发布

Does it make any difference for the garbage collector 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();
    }
}

1条回答
聊天终结者
2楼-- · 2019-03-31 07:58

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.

查看更多
登录 后发表回答