Should I use lock in the following scenario

I developed a stack wrapper class. My confusion is whether I should use the lock" ParameterStack" when the objects appear or click in the stack variable . Please let me know if 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 created this StackManager class for training.

+3
source share
5 answers

Everything looks fine. There is a (rather theoretical) argument that locking on ParameterStackits own is not completely safe, because you do not have your own code. Suppose that somewhere inside the stack there is lock(this), you can go into a dead end.

public static class StackManager
{
    private static Stack parameterStack = new Stack();
    private static object stackLock = new object();

    // now use lock(stackLock) instead of lock(ParameterStack)

}
+7
source

ConcurrentStack . ConcurrentStack - Stack.Synchronized():

Stack mySynchronizedStack = Stack.Synchronized(myStack);

Synchronized(), - , .

Stack myStack = new Stack();
lock (myStack.SyncRoot)
{
    foreach (var element in myStack)
    {
    }
}

, Stack Synchonization(). , :

public static class StackManager
{
    private static Stack ParameterStack;

    static StackManager()
    {
        ParameterStack = Stack.Synchronized(new Stack());
    }

    public static T Pop<T>()
    {
        object RawObject = ParameterStack.Pop();

        return RawObject is T ? (T)RawObject : default(T);
    }

    public static void Push<T>(T Data)
    {
        ParameterStack.Push(Data);
    }
}

object RawObject, . , Pop .

+1

, . #.

+1

, . , .

You can use Stack<T>to avoid all castings. Or, as oxilumin says, use ConcurrentStack if you're not just trying to learn how to do something thread safe.

+1
source

Do you know about the ConcurrentStack class? it is an efficient threading implementation using blocking

0
source

All Articles