StreamWriter

  • Thread starter Thread starter David Burkinshaw
  • Start date Start date
D

David Burkinshaw

I'm seeing instances in one of our programs where a StreamWriter object
writes the same data twice. It only occurs when several messages hit at the
same millisecond. We time stamp our messages.

Here is a snippet of code.

public class clsLogWriter
{
private StreamWriter sw;
private FileStream fs;
private string strFSName;

public clsLogWriter()
{
string FSName = Application.StartupPath + @"\OurLog.log";
fs = new FileStream(FSName, FileMode.Append, FileAccess.Write,
FileShare.ReadWrite, 8196, true);
sw = new StreamWriter(fs);
sw.AutoFlush() = true;
}

public void writeLogs(string p_String)
{
sw.WriteLine(p_String);

// code to create TCPClient objects and send p_String
}
}

For some reason the sw.WriteLine(p_String) will write the same line twice
when there is heavy activity but the code below which writes to a TCP Client
object writes the same data once. We had originally set the buffer to 384
bytes which is longer than our longest expected line and when we increased
it to 8196 we started noticing the problem. We also didn't have AutoFlush on
and put sw.Flush() after the WriteLine. Does anyone know of any issues with
the StreamWriter where the buffer doesn't get flushed before another string
is sent to it? We've also seen long segments of spaces showing up in the
log.

Thanks in advance,

David
 
Hey David,

If your expecting different threads to hit your streamwriter it would
be prudent to lock access to it like this:

public void writeLogs(string p_String)
{
lock(this)
{
sw.WriteLine(p_String);
}
}

Your problems probably stem from the fact that the instance methods of
the StreamWriter are not thread safe, as stated in the documention.
http://msdn.microsoft.com/library/d.../html/frlrfSystemIOStreamWriterClassTopic.asp
The different threads hitting the StreamWriter are probably leaving it
in a corupt state.

Hopw that helps,
Jan
 
Jan,
We just put the lock in like you wrote below. Earlier, we had dropped the
buffer size to 512 from 8196 and the duplicate lines increased. We'll run
our program and I'll let you know how it turns out.

Thanks,

David
 
This seems to have helped in the fact that the messages are now clean
however it appears that messages are now being missed. I'm going to have to
somehow buffer the incoming messages and let the StreamWriter do it's thing.

Thanks for you help.

David
 
Back
Top