How to handling the file concurrency issue?

M

Mullin Yu

I create a component to write the error log as follow, but it seems
sometimes locked by other processes, and pop up the I/O exception.

How can we handling the concurrency issue at file level? Retry accessing the
file if catch error => like waiting and polling.

Thanks!

private void LogError2File(string errorMessage, string LogFilePath)

{

FileInfo oFileInfo = new FileInfo(LogFilePath);

DirectoryInfo oDirInfo = new DirectoryInfo(oFileInfo.DirectoryName);


if(!oDirInfo.Exists)

oDirInfo.Create();

if(!oFileInfo.Exists)

oFileInfo.Create();

StreamWriter w = File.AppendText(LogFilePath);

w.Write("\r\nLog Entry : ");

w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),

DateTime.Now.ToLongDateString());

w.WriteLine(" :");

w.WriteLine(" :{0}", errorMessage);

w.WriteLine
("----------------------------------------------------------------");

// Update the underlying file.

w.Flush();

// Close

w.Close();

}
 
N

Nicholas Paldino [.NET/C# MVP]

Mullin,

Instead of calling AppendText, open the FileStream yourself, allowing it
to be shared for read-only access, but you maintain the write access.

Hope this helps.
 
M

Mullin Yu

do i need to implement any multiple-producer-consumer pattern at this case?

more than one process/application will write to the error log file.

what's the implementation of commercial software then? like iis log, tomcat
log?

thanks!

regards,
mullin

Nicholas Paldino said:
Mullin,

Instead of calling AppendText, open the FileStream yourself, allowing it
to be shared for read-only access, but you maintain the write access.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Mullin Yu said:
I create a component to write the error log as follow, but it seems
sometimes locked by other processes, and pop up the I/O exception.

How can we handling the concurrency issue at file level? Retry accessing the
file if catch error => like waiting and polling.

Thanks!

private void LogError2File(string errorMessage, string LogFilePath)

{

FileInfo oFileInfo = new FileInfo(LogFilePath);

DirectoryInfo oDirInfo = new DirectoryInfo(oFileInfo.DirectoryName);


if(!oDirInfo.Exists)

oDirInfo.Create();

if(!oFileInfo.Exists)

oFileInfo.Create();

StreamWriter w = File.AppendText(LogFilePath);

w.Write("\r\nLog Entry : ");

w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),

DateTime.Now.ToLongDateString());

w.WriteLine(" :");

w.WriteLine(" :{0}", errorMessage);

w.WriteLine
("----------------------------------------------------------------");

// Update the underlying file.

w.Flush();

// Close

w.Close();

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top