maz
maz

Reputation: 523

How to detect a handle leak in c# app

In my C# app , when it run i can see clearly in the windows task manager that the count of handle columns is steadly increase. The memory is fine and not increase , only the handle arrive to very high level.

How can i debug this leak , detect it and solve the handle leak.

Thanks!

Upvotes: 0

Views: 2435

Answers (1)

Brannon
Brannon

Reputation: 5414

I doubt this is something that you're going to debug; it's something you're going to find with code inspection. Possible causes:

  1. Failing to dispose of GDI objects. Are you using WinForms? Do you have using statements on every brush and pen?

  2. Is your thread count going up with the handle count? Are you starting threads that never complete?

  3. Are you using LogonUser? CloseHandle? You have to be very careful disposing user handles. If you pass the logon handle to WindowsIdentity, you should dispose the handle right after passing it to WindowsIdentity (on the same thread it was created on.)

  4. Are you using SqlConnection? It's pool maintains open handles. Maybe something is not right there.

Ages ago I had an issue where I was disposing a LogonUser handle late. In fact, the user had disconnected and the handle had been closed automatically. I would thereafter call CloseHandle on what I thought was the handle. However, the handle slots in .NET are reused. They are almost always valid, but you cannot tell what kind of object is in a given slot. I was actually closing SqlConnection pool objects inadvertently.

Upvotes: 1

Related Questions