1

What should be the best practice to lock a block of code inside a console app, so that it doesn't create any problem while running multiple instances, of executable/application

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();
Dmitry Ledentsov
  • 3,620
  • 18
  • 28
shanky
  • 376
  • 1
  • 18

1 Answers1

0

You should use a Mutex. "A synchronization primitive that can also be used for interprocess synchronization." See: Msdn

Something like:

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(); }
Eric Dahlvang
  • 8,252
  • 4
  • 29
  • 50