I had designed a Stack wrapper class. My confusion is, should I be using lock while popping or pushing objects to the stack variable “ParameterStack“. Please let me know, whether this class is thread safe or not.
public static class StackManager
{
private static Stack ParameterStack = new Stack();
public static T Pop<T>()
{
T RawObject;
T Result = default(T);
lock (ParameterStack)
{
RawObject = (T)ParameterStack.Pop();
}
if (RawObject != null && RawObject is T)
Result = (T)RawObject;
return (T)Result;
}
public static void Push<T>(T Data)
{
lock (ParameterStack)
{
ParameterStack.Push(Data);
}
}
}
I had created this StackManager class for learning purpose.
It looks OK. There is a (rather theoretical) argument that locking on
ParameterStackitself is not totally safe because you don’t own the code. Suppose somewhere inside the Stack does alock(this), you could deadlock.