The best internal check you can possibly use is the lock
setup that others have suggested. But here are some creative ways worth investigating to see if they solve your specific problem. The issue I have is, I don't know if only parts of the class is unsafe, if it's thread-safe to have different threads using different instances of the class or not. So here are some combinations of lock
that mitigate certain scenarios
Scenario 1: Static Class/Methods - This will ensure that no matter who accesses the static class/members they will be blocked if another thread is already doing so.
public static class UnsafeStaticClass
{
private static object _padLock = new object();
public static void UnsafeStaticMethod()
{
lock(_padLock)
{
// Do Work
}
}
}
Scenario 2: Normal class where instances can be paralel, but only one call per instance is allowed. Multiple instances can run the code block at the same time.
public class UnsafeClass
{
private object _padLock = new object();
public void UnsafeMethod()
{
lock(_padLock)
{
// Do Work
}
}
}
Scenario 3: A Class instance, that interracts with unsafe static methods - hence a need to ensure that only a single call to ouside static methods exists. No matter how many instances there are, only one of them can run the method at a time, since it locks on a static object.
public void UnsafeClass
{
private static object _padLock = new object();
public void UnsafeInstanceMethod()
{
lock(_padlock)
{
// Do Work
}
}
}