etienne_marais
Honorary Master
I have a static method on a static class (Program) that writes (text) to files.
This method is called from various threads running simultaneously.
I know this is not the correct solution for locking resources, but I am more curious as to why it does not work and what is actually happening.
The idea is that while the text file to be written to is in use the method sleeps until it is (or should have been) released by the OS.
If multiple thread simultaneously call this method, is it definitely true that this static method is invoked and executed in parallel ?
MessageThreadLogLocked is a static property on the static class Program.
This method is called from various threads running simultaneously.
I know this is not the correct solution for locking resources, but I am more curious as to why it does not work and what is actually happening.
The idea is that while the text file to be written to is in use the method sleeps until it is (or should have been) released by the OS.
If multiple thread simultaneously call this method, is it definitely true that this static method is invoked and executed in parallel ?
MessageThreadLogLocked is a static property on the static class Program.
Code:
public static void WriteToFileMessageThread(string meterNumber, string message)
{
message = Environment.NewLine + DateTime.Now.ToString() + message;
while (MessageThreadLogLocked)
{
Thread.Sleep(15);
}
string subdirectory1 = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\" + subdirectory1;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string subdirectory2 = "MeterLogs";
string path2 = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\" + subdirectory1 + "\\" + subdirectory2;
if (!Directory.Exists(path2))
{
Directory.CreateDirectory(path2);
}
MessageThreadLogLocked = true;
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\" + subdirectory1 + "\\" + subdirectory2 + "\\" + meterNumber + ".txt";
if (!File.Exists(filepath))
{
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(message);
}
}
Thread.Sleep(10);
MessageThreadLogLocked = false;
}
Last edited: