LINQ Query and IDisposable

I am currently writing a piece of code that performs some search queries that return IDisposable objects (DirectoryEntry to be specific from an ADAM instance), and I get code similar to

using(var entry = (from result in results let entry = result.GetDirectoryEntry() where entry != null select entry).Last()) { //blah blah } 

but who is responsible for deleting objects not returned by the above request? or more, is the code above, is there really no Dispose () call for all other entries than the last?

+4
source share
2 answers

if it is a Linq object for objects, then you are responsible. Yes, objects will not be deleted. You must execute the query results before Last and Dispose them manually.

+3
source

Disposal is based on data context. The request itself is pure .Net and does not require deletion unless you create objects that require disposal. In this case, you will need to individually call the delete device on all objects that you call.

I do not think that using linq in this situation would be appropriate since you are about to leak the resources. AFAIK they work with linq for an active directory provider, but until then, you probably will be better off trying to write your query directly in AD.

Or you can write a loop to work with resources:

 DirectoryEntry entry = null; foreach(var result in results) { //Need to add logic to deal with errors. var temp = result.GetDirectoryEntry(); if (temp != null) { if (entry != null) { entry.Dispose(); entry = temp; } else { entry = temp; } } } using (entry) { //code here } 

By the way, you should see this MSDN entry GetDirectoryEntry : Calling GetDirectoryEntry for each SearchResult returned through DirectorySearcher can be slow.

+1
source

All Articles