Visual C# Developer Center >
Visual C# Forums
>
Visual C# General
>
reference type issue (very urgent)
reference type issue (very urgent)
- 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
- 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.- Marked As Answer byChao KuoMSFT, ModeratorFriday, November 06, 2009 6:47 AM
- Proposed As Answer byChao KuoMSFT, ModeratorThursday, November 05, 2009 9:06 AM
- 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- Marked As Answer byChao KuoMSFT, ModeratorFriday, November 06, 2009 6:47 AM
- Proposed As Answer byChao KuoMSFT, ModeratorThursday, November 05, 2009 9:06 AM
All Replies
- 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.- Marked As Answer byChao KuoMSFT, ModeratorFriday, November 06, 2009 6:47 AM
- Proposed As Answer byChao KuoMSFT, ModeratorThursday, November 05, 2009 9:06 AM
- 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 - 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
- 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- Marked As Answer byChao KuoMSFT, ModeratorFriday, November 06, 2009 6:47 AM
- Proposed As Answer byChao KuoMSFT, ModeratorThursday, November 05, 2009 9:06 AM
- 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- Proposed As Answer byChao KuoMSFT, ModeratorThursday, November 05, 2009 9:06 AM
- 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();
} - 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 - 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 - 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 - 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 - 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 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- 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 ?
From client call as below/// <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; } }
LoggerManager.Instance.WriteData(@"C:\Hello.txt", "Message to log");
LoggerManager.Instance.CloseFiles();
Hope This helps
Thanks & Regards
PKR - 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 - 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 - 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


