I have a reusable logging component I use for several different projects. Some programs write log entries several times a second and I see no significant lag due to the logging. If you do an asynchronous write, your main thread will run concurrently with the log operation. See the code below for an idea on how this can be done.
using System;
using System.Text;
using System.IO;
using System.Threading;
[...].
string m_FileName;
string m_Directory;
AutoResetEvent m_FileWriteComplete;
[...].
public void Write(string msg)
{
m_FileWriteComplete.WaitOne();
FileStream fs = File.Open(Path.Combine(m_Directory, m_FileName), FileMode.Append,
FileAccess.Write, FileShare.ReadWrite);
msg = msg + "\r\n";
byte[] writeBuff = ASCIIEncoding.ASCII.GetBytes(msg);
fs.BeginWrite(writeBuff, 0, writeBuff.Length, new AsyncCallback(WriteCallBack), fs);
}
void WriteCallBack(IAsyncResult result)
{
FileStream fs = null;
try
{
fs = (FileStream)result.AsyncState;
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
m_FileWriteComplete.Set();
}
}