开发者

Thread creation scope and the garbage collector

开发者 https://www.devze.com 2023-03-14 13:05 出处:网络
Does it make any difference for the garbage coll开发者_开发技巧ector if we declare a thread at method scope rather than at class scope, like:

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.

0

精彩评论

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