Is there a memory efficient way to use 'using' within a recursive function when e.g. writing lines to a file?
I read C# 'using' block inside a loop and it mentioned that you don't want to put a using statement inside a for loop unless you have to. (makes sense, one doesn't want multiple instances of 'using' if one doesn't need them). So in the case of a for loop if you can put it outside, you do.
But here, I have a recursive function. So the 'using' statement is going to run multiple times even if I put it outside of a for.
So what is a good or proper way of placing the 'using' statement?
I don't know if I should avoid 'using', and declare the StreamWriter object, StreamWriter writetext before the method call and dispose of it after with writetext.Dispose(). Or maybe there is a more conventional way with 'using'. Maybe wrapping the 'main' call DirSearch_basic_writetofile("c:\\aaa"); with a 'try' and putting the Dispose line in a finally. And avoiding 'using' then. That's just a thought.
// requires directory c:\texts
File.Delete(@"c:\texts\filelist.txt");
// list files and subdirectories of c:\aaa and write them to file "c:\texts\filelist.txt"
DirSearch_basic_writetofile("c:\\aaa");
// recursive function that lists files and directories and subdirectories,in given directory
static void DirSearch_basic_writetofile(string sDir)
{
Console.WriteLine("DirSearch(" + sDir + ")");
Console.WriteLine(sDir+@"\");
try
{
using (StreamWriter writetext = new StreamWriter("c:\\texts\\filelist.txt",true))
{
writetext.WriteLine("DirSearch(" + sDir + ")");
writetext.WriteLine(sDir);
foreach (string f in Directory.GetFiles(sDir))
{
Console.WriteLine(f);
writetext.WriteLine(f);
}
}
foreach (string d in Directory.GetDirectories(sDir))
{
DirSearch_basic_writetofile(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
BlockingCollectionwith entries of file / directory names. Then have a second thread reading from theBlockingCollection(basically a Producer Consumer model). That way you don't even need to pass theStreamWriteraround (since it is used in only one place).using(StreamWriter writetext = new StreamWriter("c:\\texts\\filelist.txt", true)) DirSearch_basic_writetofile("c:\\aaa");(not passing the stream down the recursive calls), but still , declaring it outside of it.Console.WriteLinecalls. If you wanted to improve performance you should reduce the number ofConsole.WriteLinecalls (e.g. call it every 10 or 100 or 1000 entries (e.g. concatenating 100 entries and then writing them all to the console in one hit) rather than every entry).