I know there are some questions already raised here, but the solutions provided there are not working for me.
I am executing my automation code using parallel execution, and there are multiple threads involved in it. There are certain preconditions like setting up the environment, creating a report folder which I want to execute only once but currently, all the threads are trying to execute these preconditions which are creating a problem.
Here is my sample code. I tried to implement the solutions mentioned here.
private readonly object locker = new object();
bool IsModelLoaded = false;
public void initialize()
{
lock (this.locker)
{
if (!IsModelLoaded)
{
Console.WriteLine("PrintMsg");
IsModelLoaded = true;
}
}
}
main()
{
initialize();
}
When I am running the above code with 3 parallel threads, I am getting 3 messages in my Console. Ideally, I want only one of my threads to execute the above code.
Anything I am missing? Is there any better approach? Please suggest. Appreciate any help here.
Update:- I also tried the solutions mentioned in the link but the solutions mentioned in the link are only working when I am running the code in Debug mode. It's not working in the normal mode. Here are 2 things which I tried
- lock (lockThis) {}
- [MethodImpl(MethodImplOptions.Synchronized)]