You can use lock
keyword to prevent execution of code fragment in parallel.
Just wrap your function's calls into a lock statement or add a lock inside function itself.
class MyClass
{
private object lockObj = new();
public void MyFunction()
{
lock(lockObj)
{
//code goes here
}
}
}
//usage
void Test()
{
var myClass = new MyClass();
var thread1 = new Thread(ThreadFunc);
var thread2 = new Thread(ThreadFunc);
thread1.Start(myClass);
thread2.Start(myClass);
}
public static void ThreadFunc(object myClassObj)
{
var myClass = (MyClass)myClassObj;
myClass.MyFunction();
}
Note lockObj
object here. To acheive behaviour you want, you should use exactly the same lockObj
value in the lock
statements. So, the following is WRONG
//WRONG, do NOT DO this
var myClass1 = new MyClass();
var myClass2 = new MyClass();
var thread1 = new Thread(ThreadFunc);
var thread2 = new Thread(ThreadFunc);
thread1.Start(myClass1);
thread2.Start(myClass2);
Here we have two independent instances of MyClass
, so each instance has their own value of lockObj
and thus this instances will not lock each other, so parallel exectution of myClass1.MyFunction()
and myClass2.MyFunction()
is allowed here.