views:

180

answers:

3

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.

A: 

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.

ho1
I already suspected GC, and tried to wait a day (with my app) - nothing happened. Now I will repeat the test with test app. So far I clicked many times to get about 1K handles. Still the same number of handles after 10 min, continue waiting...
Mahno
1000 might still be too few to get it to start doing stuff, try 5-10,000 and you should see things happening right away.
ho1
Hmmm... Do I have any way to enforce GC clean up handles manually? Actualy answer like "wait for another 10K handles before they might be cleaned up by GC" will not satisfy my customer...
Mahno
You could run the `GC.Collect` as described here: http://msdn.microsoft.com/en-us/library/xe0c2357.aspxCould end up being a bit slow though.But I think the main problem is, if your customers are worried about number of handles being held by the application, they might be better of with a non managed app where you can control these things much better.
ho1
GC.Collect helps at least with my test app, thanks.
Mahno
+1  A: 

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.

Johannes Rudolph
My thread is created in mouse click hadler function locally (see an example), which means all references are dropped as soon as we leave the function. But in fact this is not the case - Handles remains.
Mahno