处理与.NET System.Threading.Thread类泄漏System、NET、Thread、Threading

2023-09-06 23:58:42 作者:阳光的

我有一个问题,在我的应用程序,句柄数的持续增长。我做了调试,并认识到这是由于它用于一些日常System.Threading.Thread类。为了简化我创建了一个示例.NET应用程序的调试:

I've a problem that number of Handles in my app is continuously growing. I did the debugging and recognize that this is caused by System.Threading.Thread class which is used for some routine. To simplify the debugging I’ve created a sample .NET application:

    ...

    private void button1_Click(object sender, EventArgs e)
    {
        Thread t = new Thread(DoWork);
        t.Start();
    }

    public void DoWork(object parameter)
    {
        // Do something...
    }

    ...

每次我点击按钮,一个线程使用System.Threading.Thread类创建。 问题是,看起来像线程不免手柄,因为手柄的每次点击的原因号码通过种植〜5。

Each time I’m clicking the button, a thread is created using System.Threading.Thread class. The problem is that looks like the thread do not frees Handles because each click cause number of Handles growing by ~5.

现在的问题是:我怎么能手动释放由System.Threading.Thread类创建的所有句柄

The question is: how can I manually free all Handles created by System.Threading.Thread class?

在此先感谢。

推荐答案

这实际上没有漏水的手柄,它只是在GC还没有收集他们没有。试着改变code。在按钮的处理,使其循环,并创建500线什么的,然后再试pressing了几次,你可能会看到所收集的句柄。

It's not actually leaking the handles, it's just that the GC hasn't collected them yet. Try changing the code in the button handler so that it loops and creates 500 threads or something and try pressing it a few times and you'll probably see handles being collected.