I am writing some class in c# that have a function
Print(string s)
In the last version i found out that this function called from many threads and every time this function called it should be locked. In C language i can rename this function to
PrintA(string s)
and change the header file to something like
#define Print(a) {Lock(PrintA) //
{ //
PrintA(a) //
} //
}
Is it possible to write something like this in C#?
I just want to change one place instead multiple place all over the code.
There are no macros in C#. To add synchronization to a method, you can use:
You’ll need to define a lock object, simply add a field to your class
[MethodImpl(MethodImplOptions.Synchronized)]is less recommended as it usesthisas the lock object, which means users can interfere with locking logic and cause deadlocks.