Msdn got good explanation, check documentation. Thread Synchronization
Since you have a static method, you need static Object
for locking.
public class Calculator
{
private static System.Object lockThis = new System.Object();
public static void Add(int a, int b)
{
lock (lockThis)
{
return a+b;
}
}
}
That lock
means, that whenever a Thread accesses that method and it is not locked, it will lock it and run the code. If it is locked it will do nothing until it is unlocked.
Edit: Edited code for your method.