Preconditions:
I have to fix synchonization issues in very big legacy spaghetty codebase. There are some classes that must be synchronized. But there are lots of usages for these classes. It is why I am looking for way to catch issues with debug guards.
There is one of ideas to report problem in usage of some classes.
Class for debug purposes:
public class AsyncChecker {
private readonly Thread myThread;
private volatile bool myTurnedOn;
public AsyncChecker() {
myThread = Thread.CurrentThread;
myTurnedOn = false;
}
public void turnOn() {
myTurnedOn = true;
}
public void checkThread() {
if ( myTurnedOn && Thread.CurrentThread != myThread ) {
Debug.LogError( "illegal thread" );
}
}
public void checkMultiThreadSafety() {
if ( myTurnedOn ) {
//there is code that can determine if method called from critical
//section or not even if we call from the same thread
//Monitor.IsEntered( ) works only if there is call from another thread
}
}
}
Some legacy class that can or cannot be accessed in concurrency:
public class SomeLogic {
private readonly AsyncChecker myAsyncChecker = new AsyncChecker();
public void logicOne() {
myAsyncChecker.checkMultiThreadSafety();
//some logic A
}
public void logicTwo() {
myAsyncChecker.checkMultiThreadSafety();
//some logic B
}
}
There is purpose:
public void someMethodInDeepLegacyCode() {
lock (someLock) {
someLogicClassInstance.logicOne();
}
}
public void anotherSomeMethodInDeepLegacyCode() {
someLogicClassInstance.logicTwo(); //there is access without synchronization,
//would like to have exception, or assertion, or error log or something else
}
Monitor.IsEntered
can be used only partially. Only if we called from different thread but not for the same.