Hi,
I have 2 different applications(Application 1 and Application 2) that have a critical area of code where only 1 application can be a time.
The solution I have come up with is to use a lockfile so the application knows about when the other application is in the critical area of code, which seems to work.
The problem:
As seen I use a while loop and Thread.Sleep(1) until it is possible to lock the file.
The problem is this Thread.Sleep(1) which consumes CPU.
However the most important problem here is that Sleep(1), 1 millisecond is to long as I use 100:s of those loops to wait for the same file.
What I wonder is if there is anyway to improve the Sleep/wait time to zero or instantly in any way?
Thank you
//Application 1
FileStream stream = null; String lockFile = "C:/lockfile.txt";
while (true)
{
try
{
//Try to Lock file
stream = new FileStream(lockFile, FileMode.Open, FileAccess.Read, FileShare.None);
break;
}
catch
{
//This is heavy for the CPU and will not respond immediately when lockfile is avaliable
Thread.Sleep(1);
}
}
//Do some work
///
///Critical area where only 1 appliation can be at a time
///
//close the lockfile
if (stream != null) { stream.Close(); }
//Application 2
FileStream stream = null; String lockFile = "C:/lockfile.txt";
while (true)
{
try
{
//Try to Lock file
stream = new FileStream(lockFile, FileMode.Open, FileAccess.Read, FileShare.None);
break;
}
catch
{
//This is heavy for the CPU and will not respond immediately when lockfile is avaliable
Thread.Sleep(1);
}
}
//Do some work
///
///Critical area where only 1 appliation can be at a time
///
//close the lockfile
if (stream != null) { stream.Close(); }