I'm working on some code to do some asynchronous logging to a text file. If
I open the file (manually) while it's being written to I get a
System.IO.Exception with the message "The process cannot access the file
(the path) because it is being used by another process. This happens
consistently with debug builds and much less with release builds.
The file io I'm doing is not asynchronous, I say the logging is asynchronous
because I fire an event which a logging function subscribes to.
I think I should be able to write to a file and not have an exception
generated when I manually open that file during some write operations but I
haven't figured out how to do that yet. TIA
Here's the code (running against 1.0 of the framework):
using System;
using System.IO;
namespace AsyncLog3
{
class Class1
{
private static object syncObject = new object();
private static int lineNum = 0;
private delegate void MyDelegate(object sender, DenaliArgs
args);
private static event MyDelegate MyEvent;
static void Main()
{
MyEvent += new MyDelegate(WriteLog);
if (MyEvent != null)
{
object sender = new object();
for (int i=0; i<1000000; i++)
MyEvent(sender, new DenaliArgs("Hello,
World"));
}
}
private static void WriteLog(object sender, DenaliArgs args)
{
string fileName = "MyLog.txt";
lock (syncObject)
{
using (FileStream fileStream = new
FileStream(fileName, FileMode.Append, FileAccess.Write,
FileShare.ReadWrite)) // System.IO.Exception in debug build
{
// System.IO.Exception in release, points to disassembly, less frequent
using (StreamWriter writer = new
StreamWriter(fileStream))
{
writer.WriteLine("{0}: {1}", ++lineNum,
args.Str);
Console.WriteLine("{0}: {1}", ++lineNum,
args.Str);
writer.Flush();
}
}
}
}
}
}
===================================
This list is hosted by DevelopMentorĀ® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com