1

在控制台应用程序中锁定代码块的最佳做法应该是什么,以便在运行多个可执行文件/应用程序实例时不会产生任何问题

string folder = Convert.ToString(ConfigurationManager.AppSettings["LogFilePath"]);
string configFile = Path.Combine(folder, "logger.xml");
FileStream fs = new FileStream(configFile, FileMode.Open);
log4net.Config.XmlConfigurator.Configure(fs);
fs.Close();
4

1 回答 1

0

您应该使用互斥锁。“一种同步原语,也可用于进程间同步。” 见:Msdn

就像是:

var mutex = new Mutex(false, "logger.xml-mutex");
if (!mutex.WaitOne(TimeSpan.FromSeconds(100), false))
{
    Console.WriteLine("Timed out...could not acquire mutex.");
    return;
}
try
{
    string folder = Convert.ToString(ConfigurationManager.AppSettings["LogFilePath"]);
    string configFile = Path.Combine(folder, "logger.xml");
    FileStream fs = new FileStream(configFile, FileMode.Open);
    log4net.Config.XmlConfigurator.Configure(fs);
    fs.Close();
}
finally { mutex.ReleaseMutex(); }
于 2013-01-22T14:48:54.163 回答