[Mono-devel-list] (no subject)

Chris Turchin chris at turchin.net
Sun Jan 11 07:36:20 EST 2004


Hi David,

You can avoid this problem by using the 'using' statement when working
with objects implementing the IDisposable interface (reader/writers
being a prime example):

try {
	using(XmlValidatingReader xvr = new XmlValidatingReader (new
XmlTextReader(filename)))
	{  
		while(!xvr.EOF)     	
			xvr.Read();   
		xvr.Close();
	}
}...

then the GC should dispose of them automatically when their scope
expires... even if you don't call Close();

This code ran fine:

using System;
using System.IO;
  
class Test 
{
	static void Main(string[] args)
	{
	 
		for (int i = 0; i<20000;i++) 
		{
			using (TextReader r = File.OpenText("log.txt")) 
			{
				string s;
				while ((s = r.ReadLine()) != null) 
				{
					//do something, or not...
				}
			}
		}
		Console.WriteLine("end");
	}
}


Regards,
--chris

On Sun, 2004-01-11 at 13:08, David Sheldon wrote:
> Hi, I have been running some tests that involve reading a lot of files
> and processing them one by one. 
> 
> My code was something like this:
> 
> try {
>   XmlValidatingReader xvr = new XmlValidatingReader (new XmlTextReader(filename));
>   while(!xvr.EOF) 
>     xvr.Read();
>   xvr.Close();
> } 
> catch (XmlSchemaException ex) {
>   // print error
> }
> 
> Being a sort of lazy programmer, I didn't close the reader in a finally
> block. Well, I couldn't really, as it was out of scope there, so I left
> the scoping to deal with closing it.
> 
> A lot of these files failed for some reason, and I ended up getting
>   "Unhandled Exception: System.IO.IOException: Win32 IO returned
>    ERROR_NO_MORE_FILES."
> 
> Which surprised me as I didn't expect a Win32 IO error on linux, but
> basically it meant that I had run out of per-user file handles (limited
> to about 2000 under my install).
> 
> So what had happened was that there were a whole load of out-of-scope
> objects using up these resources. 
> 
> Would it be possible for a garbage collect to be forced when we run out
> of other resources like this, not just ram, to possibly free some up?
> 
> David
> 
> A simple example case - pass it the name of an existing file :
> 
> using System.IO;
> 
> class OpenTest 
> {
>   static void Main(string [] args )
>   {
>     for (int i = 0; i<20000;i++) {
>       TextReader r = new StreamReader(args[0]);
>     }      
>   }
> } 
> 



More information about the Mono-devel-list mailing list