el uso de palabras clave ocupa menos espacio?

Is it true that if i use the following, it will take less resources and the cleanup will be faster?

 using (TextReader readLogs = File.OpenText("C:\\FlashAuto\\Temp\\log.txt"))
 {
      //my stuff
 }

en comparación con:

 TextReader readLogs = new StreamReader("C:\\FlashAuto\\Temp\\log.txt");
 //my stuff
readLogs.Close();
readLogs.Dispose();

preguntado el 08 de noviembre de 11 a las 10:11

2 Respuestas

The difference between those examples isn't performance, but exception safety. using crea un try...finally block in the background.

A using statement of the form:

using (ResourceType resource = expression) embedded-statement 

corresponds to the expansion:

{ 
   ResourceType resource = expression; 
   try {     
     embedded-statement 
   } 
   finally { 
     // Dispose of resource 
   } 
}

For reference type the disposing happens via:

finally {  
  if (resource != null) ((System.IDisposable)resource).Dispose(); 
}

From ECMA-344 C# Language Specification 4th Edition


You also don't need to call both Close y Dispose. Those functions are equivalent.

Respondido el 20 de junio de 20 a las 12:06

Actually im doing some logging stuff after every 10 seconds in the UI thread. Every time it reads the log and displays in a multiline textbox, a huge chunk of memory is taken. But if i update the textbox without reading file by using some status message of my own, there is no change in the memory. - Rohan

@musefan the quote formatting was deliberate, since these are quotes from the spec. - CódigosInChaos

Fair enough, should probably add references at point of posting next time though, avoid confusion for innocent readers ;) - musefan

The first sample is short-hand for:

TextReader readLogs = File.OpenText("C:\\FlashAuto\\Temp\\log.txt");
try
{
    // My stuff
}
finally
{
    if (readLogs != null)
    {
        ((IDisposable)readLogs).Dispose();
    }
}

Its not that its quicker, its that readLogs will be cleaned up even if an exception occurrs which won't happen in your second example.

Consulte nuestra página using Statement (Referencia de C #) para obtener más información.

There is no need to call both Close y Dispose, internamente el Close method does the same work as the Dispose method (its just renamed because developers are used to having a method called Close).


Actualizar: There is also no difference between calling File.OpenText y new StreamReader - internally File.OpenText just creates and returns a new instance of StreamReader.

respondido 08 nov., 11:14

Actually im doing some logging stuff after every 10 seconds in the UI thread. Every time it reads the log and displays in a multiline textbox, a huge chunk of memory is taken. But if i update the textbox without reading file by using some status message of my own, there is no change in the memory. - Rohan

@Rohan It sounds like the difference is in the // My stuff bit - if you are reading the entire file every time then this probably will use up a chunk of memory. - Justin

File.OpenText debe estar fuera del try...finally block. Your code wouldn't compile because readLogs isn't guaranteed to be initialized in your finally clause. - CódigosInChaos

@Justin: you were right. Changing //my stuff did the job. Thanks for all the help - Rohan

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.