Jump to content

How to Close Resources Instantiated in Try Block?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
ibad

ibad

    Learning Programmer

  • Members
  • PipPipPip
  • 39 posts
I'm having a terrible time trying to close readers or streams or web-responses that get instantiated in a try block.

basically my try block is enclosed in a loop that implements retries upon failure. But everytime I open various connections and get responses, if the try block throws and exception and I have to repeat the whole thing I get a memory leak right?

But if i try to close these various items in the catch or finally block, I get a compile time error that tells me they have not bee instantiated. I tried using dummy instatiations, but this can be tricky for some items and I don't want to do it.

Here is the code:



      try

         {


                ftpRespStream = ftpResp.GetResponseStream();


 


                reader = new StreamReader(ftpRespStream);


                fileConts = reader.ReadToEnd();


            }


            catch (Exception ex)


            {


               


            }


            finally


            {


                if (ftpRespStream != null)


                {


                    ftpRespStream.Close();


                }


 


                if(reader != null)


                {


                    reader.Close();


                }


            }



Also, if I exit the method and just have method "retried" from external calls rather than implementing retries in the method, would that ensure that any streams, connections, responses or readers get disposed? Would that be a viable approach instead of this?

Most importantly, what could I do here to close these items?

Thanks!

#2
lobo521

lobo521

    Learning Programmer

  • Members
  • PipPipPip
  • 57 posts
try something like that:

using(ftpRespStream = ftpResp.GetResponseStream())
using(reader = new StreamReader(ftpRespStream))
fileConts = reader.ReadToEnd();


When u use "using" clausule on IDisposable it frees all resources.

About this compile time error try somethig like that:


StreamReader sr;

try
{
sr = new StreamReader(ftpResp.GetResponseStream())
}
finaly
{
sr.Close();
}

Variables has to be visible in thier blocks.