Amit Barkai
Amit Barkai

Reputation: 51

DirectoryEntry instance are not disposed in LDAP

I'm not sure if that is the expected behavior, but I would expect it to act differently.

After running the following code

using (var directoryEntry = new DirectoryEntry(
    directoryPath,
    ConfigurationManager.AppSettings["ldapUsername"],
    ConfigurationManager.AppSettings["ldapPassword"],
    AuthenticationTypes.Anonymous))
{
    // ldap query
}

When the query is executed and, as I would expect, I could see an active session on the LDAP.

Run the following command on the LDAP machine:

netstat -nat | findstr my_ip_address | findstr :389

I could see an active session on the LDAP:

TCP ldap_ip_address:389 my_ip_address:24730 ESTABLISHED InHost 

But when we get out from the using section and the DirectoryEntry / DirectorySearcher are disposed, I would expect the session to be closed. Still when I run the netstat command again, I could see the same active session.

Is there any reason why the session is not disposed in the LDAP? Is this a known issue?

Upvotes: 0

Views: 198

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 41008

One of two things could be happening.

  1. The connection is actually closed. The second time you run netstat, if the connection state shows CLOSE_WAIT or TIME_WAIT instead of ESTABLISHED, then this is the case: the connection was indeed closed. The connection is held in that state for a time in case some packets for that connection arrive late.

  2. DirectoryEntry is a wrapper around the native Windows Active Directory Services Interfaces (ADSI). That has some per-process connection caching built in. So if you have another non-disposed DirectoryEntry in your application that uses the same connection, then disposing a second DirectoryEntry will not close that connection. The connection stays open as long as there is at least one non-disposed DirectoryEntry in your application.

Upvotes: 0

Related Questions