So I have a class with a few methods which all use locking in order to prevent weird things happening when someone uses an instance of my class with multiple threads accessing it:
public class SomeRandomClass
{
private object locker = new object();
public void MethodA()
{
lock (locker)
{
// Does something
MethodB();
}
}
public void MethodB()
{
lock (locker)
{
// Does something else
}
}
}
As we can see, MethodB()
is automatically accessed by MethodA()
, but that won't work since MethodA()
has currently locked the locker object.
I want to make MethodB()
accessible publicly, so you can call it manually whenever needed, but I do NOT want it to be used while MethodA()
is doing things (that's why I'm using a locker object).
And of course I do not want MethodA()
to do things while MethodB()
is doing stuff. I basically want only one of all the methods to be used at the same time, but MethodA()
needs to access MethodB()
somehow without removing the lock (so that it stays completely thread-safe the whole time).
I really hope it is kind of understandable what I'm trying to ask... If there's any questions about my question, then please go ahead and post them below. Answers/Solutions are very much appreciated as well!
The solution is probably incredibly easy and I'm just not seeing it.
By the way, the above is supposed to be C#-code.