Handle leaks with .NET System.Threading.Thread class

佐手、 提交于 2020-01-06 06:55:39

问题


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...
    }

    ...

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.

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

Thanks in advance.


回答1:


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.




回答2:


Its a bug in the CLR

https://connect.microsoft.com/VisualStudio/feedback/details/430646/thread-handle-leak#tabs




回答3:


You don't need to manually free your thread handles, simply dropping all references to your Thread instance should suffice. Given that the thread is no longer running and all references to it are removed, the gargabe collector will free the handles on the next collection.

In your case, it doesn't look like the thread will ever finish.



来源:https://stackoverflow.com/questions/2895821/handle-leaks-with-net-system-threading-thread-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!