Windows服务中的文件访问
问题描述:
我有一个Windows服务,它有8个计时器并行运行(耗费时间= 10秒),每个计时器正在执行一些活动,并在进入计时器时记录write_time
,并在退出计时器时记录end_time
,这发生在所有的定时器上。 我有一个ASP.net应用程序,它为每个计时器读取write_time
和end_time
的日志,并将其显示在网格上。Windows服务中的文件访问
通常我得到一个文件操作错误,导致我的计时器停止。代码块在下面。
Write_time
FileInfo file = null;
StreamWriter write = null;
try
{
file = new FileInfo(ConfigurationManager.AppSettings["SupportFilePath"].ToString() + processName + "_Log.txt");
write = new StreamWriter(file.FullName);
write.Write(string.Empty);
write.Write(processName + "_" + time + " at: _" + System.DateTime.Now.ToString());
write.Close();
write.Dispose();
}
catch (System.Exception ex)
{
_errorMonitoringEngine.ErrorInfo(" ", ex.StackTrace.ToString(), ex.Message, "Email Notification Engine", "WriteTimeProcess2");
}
我得到maximun倍以外The process cannot access the file
。请告知如何摆脱它。
答
最有可能两个或更多的线程试图同时写入同一个文件。
创建一个object
的实例,在你的类中的某个地方以及lock
中,每当你需要写入该文件时。
public class Example
{
// ...
// Depending on whether there are one or many instances of
// this class determines whether this needs to be static
// or not. If it needs to be static, use a static constructor.
private object syncObject = new object();
// ...
void WriteToFile()
{
lock (syncObject)
{
// Do file IO
// Now no two threads will attempt to access the file at the same time
}
}
// ...
}
这也将是明智的包裹StreamWriter
在using
声明。