Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly disposing resources when connecting to LDAP using C# Directory Services

It seems to me that one should always properly dispose resources when calling Directory Services API with no exception (yet many samples, blogs and tutorials often ignore, or do one way with this call, and the other way with another call). Since all of the following DS classes implement the Dispose method, so I just want to confirm once and for all:

using (DirectoryEntry dirEntry = new DirectoryEntry()) 
{
    using (DirectorySearcher dirSearcher = new DirectorySearcher())
    {
        dirSearcher.SearchRoot = dirEntry;
        dirSearcher.Filter = ...;
        using (SearchResultCollection src = dirSearcher.FindAll())
        {
            //Other code that deals with result
        } 
    }
}

should always be done. Am I running into any risk by always systematically and religiously doing the above?

like image 662
cathat Avatar asked Jan 23 '23 11:01

cathat


1 Answers

It's actually very important to dispose Directory Services objects - many of them wrap COM+ resources and you will cause resource leaks if you fail to dispose.

So yes, you're doing the right thing, definitely, and no, there's no risk when you wrap them in using.

like image 133
Aaronaught Avatar answered Jan 25 '23 01:01

Aaronaught