I have here a small question.
I wrote a small multi threaded app which doesnt do much, it just connects to some resource,
reades few fields writes them to log and that is it.
What i would love to know if everything is being logged or not.
Here is the code for logging:
private TextWriter textWriter;
private TextWriter errorWriter;
public Logger(string filePath, string errorLogFile)
{
textWriter = TextWriter.Synchronized(File.AppendText(filePath));
errorWriter = TextWriter.Synchronized(File.AppendText(errorLogFile));
}
public void WriteToLog(string text)
{
textWriter.WriteLine(text);
}
...
So when let say i have 100 threads will this manage all data being written to log or will it skip some threads?
I will create an instance of logger in main and pass it to executor:
for (int i = 0; i < threadNumber; i++)
{
Executor executor = new Executor(logger)
}
No skipping does occur. Your code is thread safe.
You are using
TextWriter.Synchronizedto create a thread safe wrapper for writing to your file. The synchronizedTextWriteris implemented using the[MethodImpl(MethodImplOptions.Synchronized)]attribute which basically is the same as doing a lock on the instance this method is contained in.That being said, the locking that happens causes all other threads to wait until the one thread that is currently writing is finished doing so.
A better approach would be to create a class that contains a thread safe non-blocking queue where you put your log entries to and one thread that processes them and puts them into the log file. If a lot of logging is going on in your application that will most likely increase the performance.