cannot write to file which is busy by another process exp, multi Threading
Hello i have problem with putting logs using multithreading, my function loks like this
public static void AddToLog(string message)
{
using 开发者_JAVA百科(FileStream fs = new FileStream(ExeDir + @"\logs.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter mStreamWriter = new StreamWriter(fs))
{
mStreamWriter.BaseStream.Seek(0, SeekOrigin.End);
mStreamWriter.WriteLine(message + " at " + DateTime.Now.ToLongTimeString() + "." +
DateTime.Now.Millisecond);
mStreamWriter.Flush();
}
}
}
And well , i create this object each time, so i can't lock it, problem is when i am opening it, what is the best way to do it?
I have problem with putting logs using multithreading
You should use a logging library. There are many available for .NET, such as log4net. See also:
- What is your .NET logging framework of choice?
If you want to implement it yourself then factor the logging out of your application into a single component. Open the file once when your application starts and perform the logging via a well defined interface with the appropriate synchronization in the implementation. Don't directly write to the same log file from lots of different places in your application.
Your method is already static, if you are using one instance of the application just add
private static object logLock = new object();
public static void AddToLog(string message)
{
lock(logLock) // or with a timeout
{
...
But I think @Mark has the better advice to use a special library.
Take a look at the FileShare modifier as well (http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx)
(but +1 for logging library suggestions)
精彩评论