I want to create method for getting file Stream by file name and expect that my method can work with multithreading but it fails… My code here:
public static class FileHelper
{
private static object lockObject = new object();
private static Stream fileStream;
public static Stream GetFileStream(string filename)
{
if (fileStream != null)
return fileStream;
lock(lockObject)
{
if (fileStream != null)
{
return fileStream;
}
fileStream = File.OpenRead(filename);
return fileStream;
}
}
}
Possibly what you are looking for is a thread-safe singleton pattern implementation. Here is a good article of how to do it in java, but it’s pretty much the same in C#.
http://www.ibm.com/developerworks/java/library/j-dcl/index.html