.net - How to properly dispose objects created with LINQ -


i have following method creates instances of objects disposable.

public overridable sub transformxmldocumentstofilestream(byval stream system.io.stream, byval xmldocuments ienumerable(of string), byval transformcontext xsltransformcontext)     dim readers ienumerable(of xmlreader) = _         (from document in xmldocuments _          select xmlreader.create(new system.io.stringreader(document)))      transformcontext          transformxmldocumentstofilestream(stream, readers, transformcontext)     end end sub 

i iterate on objects in method:

for each reader in readers     using reader         transform.transform(reader, writer)     end using next 

the visual studio code analyzer giving warning:

ca2000 : microsoft.reliability : in method 'transformhelper.transformxmldocumentstofilestream(stream, ienumerable(of string), xsltransformcontext)', object 'new stringreader(document)' not disposed along exception paths. call system.idisposable.dispose on object 'new stringreader(document)' before references out of scope.

since there no reference stringreader, cannot put in using block or otherwise dispose it. ok ignore warning? stringreader should disposed when reader goes out of scope , garbage collected, correct?

sorry answer in c#. simple way manage idisposables make method calls new, call dispose.

list<stringreader> stringreaders = new list<stringreader>();   //note: select deferred.  stringreaders captured. ienumerable<xmlreader> readers =   xmldocuments.select(document =>   {     stringreader sr = new system.io.stringreader(document);     stringreaders.add(sr);     return xmlreader.create(sr);   }); try {   //this method enumerates readers, causing of allocations.   transformxmldocumentstofilestream(stream, readers, transformcontext); } {   foreach(stringreader x in stringreaders)   {     x.dispose();   } } 

Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -