I have code in my ASP.NET site that must not be run by 2 threads or processes concurrently, so I put it in a lock. This works assuming there is only one process, and since 'Maximum Worker Processes' is set to 1 in IIS, I felt that this is reasonable. However I did an experiment that makes me wonder:
I created this action:
public void Test()
{
for (int i = 0; i < 100; i++)
{
System.IO.File.AppendAllText(@"c:\tmp\d.txt", $"a: {i}\n");
System.Threading.Thread.Sleep(1000);
}
}
and called it from my browser. I then switch a:
to b:
, compiled it, and called it from another browser tab. Then I opened d.txt
, and I saw something like this:
b: 31
a: 67
b: 32
a: 68
b: 33
a: 69
Clearly there are 2 processes running at the same time, and my lock will not be enough. What is the best method of ensuring that my piece of code is not run concurrently?