线程的创建范围和垃圾收集器 [英] Thread creation scope and the garbage collector

查看:105
本文介绍了线程的创建范围和垃圾收集器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这会让垃圾收集任何区别,如果我们在方法范围,而不是在类范围声明一个线程,如:

  //方案1 
公共类Foo
{
公共美孚()
{
新的Thread(()=> / *引擎* /){的IsBackground =真}。开始();
}
}

//方案2
公共类酒吧
{
私人只读主题_engineThread = NULL;

公开栏()
{
_engineThread =新的Thread(()=> / * *发动机/){=的IsBackground真实};
_engineThread.Start();
}
}


解决方案

是的 - 在第一种方法中,对象将尽快底层的线程已经完成符合垃圾收集



在第二个方法,如果酒吧的实例仍然的符合垃圾收集,这将阻止被垃圾收集线程对象。我怀疑,将有底层操作系统线程上任何影响,请注意



我不认为对GC的影响,虽然 - 我会专注于可读性。你需要某种原因到后台线程参考?如果是这样,去与第二种方法,使其提供给您。如果你的的需要,这将是毫无意义的有它作为一个字段。


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();
    }
}

解决方案

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.

这篇关于线程的创建范围和垃圾收集器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆