Visual C# Developer Center > Visual C# Forums > Visual C# General > reference type issue (very urgent)
Ask a questionAsk a question
 

Answerreference type issue (very urgent)

  • Monday, November 02, 2009 5:32 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    hello
                 i have created a function writing, see the code below . if i called this function 2 time and pass different path. will i loss the first FileStream  object reference and GC when it will run empth it


    void writing(string msd,string  path)
    {

     filepath = "d:/" + path + ".txt";
     UnicodeEncoding uniEncoding = new UnicodeEncoding();
     FileStream s = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     s.Seek(0,SeekOrigin.End);
     s.Write(uniEncoding.GetBytes(msg), 0, uniEncoding.GetByteCount(msg));
     s.Write(uniEncoding.GetBytes("\r\n"), 0, uniEncoding.GetByteCount("\r\n"));
     s.Flush();

    }
    It's Me

Answers

  • Monday, November 02, 2009 5:59 AMTrecius Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Yes, you will lose the first FileStream object.  However, you don't know when GC will actually collect it, but the short note is that you will lose the FileStream.

    Hope this helps.


    Trecius

    P.S.  You might want to .Dispose() the FileStream before you leave the function or use the "using (FileStream s = new (...)) { ... }"  The using keyword will automatically dispose the object when it's done.
  • Monday, November 02, 2009 6:14 AMVic Vega Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Hi,
          You will lose the filestream object since the scope is only local to method. Once the method is executed, the object is marked to be collected by GC.
    Is there any issues ?


    Thanks
    PKR

All Replies

  • Monday, November 02, 2009 5:59 AMTrecius Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Yes, you will lose the first FileStream object.  However, you don't know when GC will actually collect it, but the short note is that you will lose the FileStream.

    Hope this helps.


    Trecius

    P.S.  You might want to .Dispose() the FileStream before you leave the function or use the "using (FileStream s = new (...)) { ... }"  The using keyword will automatically dispose the object when it's done.
  • Monday, November 02, 2009 6:08 AMGanesh Ranganathan - Bangalore, India Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Since s is a local variable, it will be lost the minute the writing function's execution ends and available for the GC.

    Each time you call it, a new FileStream object will be created. Do you want to reuse the same object?
    Ganesh Ranganathan
    [Please mark the post as answer if it answers your question]
    blog.ganeshzone.net
  • Monday, November 02, 2009 6:11 AMBharath kumar Y.S Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    s..you will lose better return the file stream from the function and store it in another variable..so that you wont lose the file stream
  • Monday, November 02, 2009 6:14 AMVic Vega Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Hi,
          You will lose the filestream object since the scope is only local to method. Once the method is executed, the object is marked to be collected by GC.
    Is there any issues ?


    Thanks
    PKR
  • Monday, November 02, 2009 6:47 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Proposed Answer
    hello
             thanks for reply what if i declare the filestream out side the method OR create object out side the method

    1).......................

     FileStream s = null;

    void writing(string msd,string  path)
    {

     filepath = "d:/" + path + ".txt";
     UnicodeEncoding uniEncoding = new UnicodeEncoding();
    s = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     s.Seek(0,SeekOrigin.End);
     s.Write(uniEncoding.GetBytes(msg), 0, uniEncoding.GetByteCount(msg));
     s.Write(uniEncoding.GetBytes("\r\n"), 0, uniEncoding.GetByteCount("\r\n"));
     s.Flush();

    }

    OR

    2),,,,,,,,,,,,,,,,,,,,,,,,,,,,

    FileStream s = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);

    void writing(string msd,string  path)
    {

     filepath = "d:/" + path + ".txt";
     UnicodeEncoding uniEncoding = new UnicodeEncoding(); 
     s.Seek(0,SeekOrigin.End);
     s.Write(uniEncoding.GetBytes(msg), 0, uniEncoding.GetByteCount(msg));
     s.Write(uniEncoding.GetBytes("\r\n"), 0, uniEncoding.GetByteCount("\r\n"));
     s.Flush();

    }


    It's Me
  • Monday, November 02, 2009 6:52 AMVic Vega Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Approach 2. Make sure that you close the file when the object is ready for dispose. May be a method Close having below code :

    void Close()
    {
        s.Close();
    }

  • Monday, November 02, 2009 7:35 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    what if i do this

     FileStream s = null;

    void writing(string msd,string  path)
    {

     filepath = "d:/" + path + ".txt";
     UnicodeEncoding uniEncoding = new UnicodeEncoding();
    s = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     s.Seek(0,SeekOrigin.End);
     s.Write(uniEncoding.GetBytes(msg), 0, uniEncoding.GetByteCount(msg));
     s.Write(uniEncoding.GetBytes("\r\n"), 0, uniEncoding.GetByteCount("\r\n"));
     s.Flush();

    }

    It's Me
  • Monday, November 02, 2009 8:05 AMGanesh Ranganathan - Bangalore, India Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Even if you do this, you will have different FileStreams created every time you call the Writing method.

    I suggest you instantiate the FileStream outside the class and pass it to the method.
    Ganesh Ranganathan
    [Please mark the post as answer if it answers your question]
    blog.ganeshzone.net
  • Monday, November 02, 2009 8:11 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    thanks for reply let say i run time method 2 million time, so do i have to worry memory shortage or any other issue ,,, b/c i belive GC willl remove the pervious filestream object when gc called


    It's Me
  • Monday, November 02, 2009 8:15 AMGanesh Ranganathan - Bangalore, India Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Is it going to be the same file 2 million times? opening and closing a filestream that many times would be a huge performance hit.

    Can you tell exactly how you want to write in your file. Maybe a better approach can be worked out without having to open and close filestreams this many times.
    Ganesh Ranganathan
    [Please mark the post as answer if it answers your question]
    blog.ganeshzone.net
  • Monday, November 02, 2009 8:33 AMVic Vega Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    As Ganesh said, opening and closing file is a major hit at perforamance. You need to design such that the file is opened and closed only once. All other time, it will just Write to the file. Explain your problem in detail so that we can help in providing a solution.

    Thanks
  • Monday, November 02, 2009 9:27 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    there will be different file , also i want to open the file once and close when application end .

    look i am getting data form socket if i get the data of product name ABC i will write to ABC if i get the data of product XYZ i will write to XYZ ,,, and at run time i will get different data...

    for example
    first time i get ABC data
    second time XYZ data
    then third time ABC data again


    and so on i have 200+ product


    It's Me
  • Monday, November 02, 2009 12:23 PMVic Vega Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code
    Hi,
      This means the request will be for different file to be written. This is more of design issue. First, Is there high possibility will be rewritten?

    One way to to design a LoggerManager Class which will hold handles to file on basis of name. So when the file handle does not exist, it creates and returns. A single ton class can be used. But make sure that locking is proper in the class. I have tried, you can something like below. it depends on the number of requests to write to the same file.

    can there be multiple write at same time ?
    	/// <summary>
    	/// SingleTon Class. Class is not thread safe
    	/// </summary>
    	class LoggerManager
    	{
    		static private LoggerManager instance;
    		private IDictionary<string, FileStream> FileLoggers = new Dictionary<string, FileStream>();
    		private LoggerManager()
    		{
    		}
    
    		/// <summary>
    		/// Use this to access this class
    		/// </summary>
    		public static LoggerManager Instance
    		{
    			get
    			{
    				if (instance == null)
    					instance = new LoggerManager();
    				return instance;
    			}
    		}
    
    		/// <summary>
    		/// Write Data to file. If you lock it on basis of file.
    		/// </summary>
    		/// <param name="FileName"></param>
    		/// <param name="Message"></param>
    		public void WriteData(string FileName, string Message)
    		{
    			FileStream fs = this.GetFileStream(FileName);
    			System.Diagnostics.Debug.Assert(fs != null, "Did not get a File handle");
    		}
    
    		/// <summary>
    		/// Close all files.
    		/// </summary>
    		public void CloseFiles()
    		{
    			foreach (KeyValuePair<string,FileStream> Data in this.FileLoggers)
    			{
    				Data.Value.Close();
    			}
    		}
    
    		/// <summary>
    		/// Get a file stream.
    		/// </summary>
    		/// <param name="FileName"></param>
    		/// <returns></returns>
    		private FileStream GetFileStream(string FileName)
    		{
    			FileStream fs;
    			if (!FileLoggers.TryGetValue(FileName, out fs))<br/>			{
    				fs = new FileStream(FileName, FileMode.Append);<br/><span style="font-size:x-small;color:#0000ff"><span style="font-size:x-small;color:#0000ff"><font size=2 color="#0000ff"><font size=2 color="#0000ff"><p>				this</p></font></font></span><font size=2 color="#0000ff"><p> </p></font></span><p><span style="font-size:x-small">.FileLoggers.Add(FileName, fs);</span></p>			}
    			return fs;
    		}
    	}
    
    From client call as below

     

    LoggerManager.Instance.WriteData(@"C:\Hello.txt", "Message to log");

     

    LoggerManager.Instance.CloseFiles();
    Hope This helps

    Thanks & Regards
    PKR

  • Wednesday, November 04, 2009 6:04 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    many thank for reply ,, i don't want to reuse the same obj .....

    please note that in my writing method i have not "close" the file will GC be able to collect it

    regards

    It's Me
  • Wednesday, November 04, 2009 6:15 AMIt_s Meee Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    many thank for reply , excellent code .

    but i want to know in your code i have holding filestream obj in dictionary .... and use that filestream obj when i want to write to the file...


    what if i create filestream obj every time when writing method is called and since filestream is a local variable it will be avaiable for GC after i complete the method

    but please note i have not called close

    what wrong in this approach
    It's Me
  • Wednesday, November 04, 2009 6:41 AMVic Vega Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi,
        it is bad coding pratice for waiting GC to collect the file handles. I prefer using "using" block for defining scopes for file handlers. If you keep filestream at method scope, then file will be opened and closed everytime. Since you have mentioned that it will be executed around million times, I see your program running into performance issues.

    The code I wrote to open the file first time and close it using the API. May be you can implement IDisposable and call call CloseFiles from Dispose method.

    YOu mentioned that you don't close the file, then how is it closed?

    Thanks
    PKR