We have a heavily used .Net 3.5 application that reads "expensive to create" data and caches it. However we are getting a lot of errors around both reading the cache file and writing to the cache file. Some of the advice that I have got from StackOverflow forums is to:
- a. read the file in "FileShare.Read" mode and write to the file in "FileShare.ReadWrite" mode. (What should the "FileAccess" mode should be used when the system is doing the read\write operation.)
- b. Use "GC.Collect" after each Read and and write operation.(What are the performance implications of doing this after each read\write operation.)
Is this a correct way of reading and writing files? Please advise.
private XmlDocument ReadFromFile(string siteID, Type StuffType)
{
XmlDocument result = null;
var fsPath = FileSystemPath(siteID, StuffType.Name);
result = new XmlDocument();
using (var streamReader = new StreamReader(fsPath))
//using (var fileStream = new FileStream(fsPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
result.Load(streamReader);
}
//GC.Collect();
return result;
}
private readonly object thisObject = new object();
private void WriteToFile(string siteID, XmlDocument stuff, string fileName)
{
var fsPath = FileSystemPath(siteID, fileName);
lock (thisObject)
{
//using (var fileStream = new FileStream(fsPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var streamWriter = new StreamWriter(fsPath))
{
stuff.Save(streamWriter);
}
//GC.Collect();
}
}