Event Handles “leak”

On our stress run, we saw our process’ handle count steadily increases until certain point, then it stabilizes. However the number of handles is high. Most of those handles are Event handles. We are concerned about it. So we went off and did some investigation.

Turns out the Event handles are coming from the use of Monitor.

When there is contention on the lock object, CLR internally creates an Event handle, presumably to facilitate the thread scheduling. The event handle is not cleaned up until the object is garbage collected.

It appears we were using Monitor in a lot of places, and we had lock contentions, which triggers CLR to allocate a lot of Event handles.

So if you have a lot of long lived objects, be careful about the usage of Monitor.

Comments (3)

  1. Barry Kelly says:

    Damn! I thought those event handles were multiplexed, only in use while there was contention. That’s somewhat disturbing: the events are sticky to the objects once contention triggers event creation.

    This seems to demand the creation of some kind of new critical-section-like primitive to prevent handle starvation in the medium term, until the CLR fixes this issue.

  2. Lucian Bargaoanu says:

    Interesting. I had the same problem once and I had no idea how to track down those "leaking" events. It would be nice to know how it can be done :). I assumed they were used by some critical sections in unmanaged code.