Search code examples
c#performanceload-testingwebtest

Load Tests Exception "file is being used by another process" C#


I'm using Visual Studio WebPerformance Tool and my problem is that all of my web-tests are working perfectly but when I run Load test (100 users) I'm getting an exception "The process cannot access the file because it's being used by another process". My conclusion is that concurrent users are trying to read the same file at the same time.

Code that did not work under the load:

int x; //user number
if(File.Exists("C:\\Users\\Desktop\\Tests\\users5a.txt"))
{
    var last_number = File.ReadAllLines("C:\\Users\\Desktop\\Tests\\users5a.txt").Last();
    x = int.Parse(last_number) + 1;
}
else
    x = 0;

System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Desktop\\Tests\\users5a.txt", true);
file.WriteLine(x);
file.Close();

Solution

  • This worked:

     EventWaitHandle waitHandle = new EventWaitHandle(true,EventResetMode.AutoReset, "SHARED_BY_ALL_PROCESSES");
    
        waitHandle.WaitOne();
    
        int x; //user number
        if (File.Exists("C:\\Users\\Desktop\\Tests\\users5a.txt"))
        {
            var last_number = File.ReadAllLines("C:\\Users\\Desktop\\Tests\\users5a.txt").Last();
            x = int.Parse(last_number) + 1;
        }
        else
            x = 0;
    
        System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Desktop\\Tests\\users5a.txt", true);
        file.WriteLine(x);
        file.Close();
        file.Dispose();
        waitHandle.Set();