I am trying to create a data structure around a stack that locks until the stack has an available item. I tried using AutoResetEvent, but I think I misunderstood how this synchronization process works. Basically, looking at the following code, I try to pop out of the stack when nothing is available.
It seems to AutoResetEventbehave like a semaphore. It's right? Can I just get rid of Set()in BlockingStack.Get()and do with it? Or this will lead to a situation where I use only one of my stack elements.
public class BlockingStack
{
private Stack<MyType> _internalStack;
private AutoResetEvent _blockUntilAvailable;
public BlockingStack()
{
_internalStack = new Stack<MyType>(5);
_blockUntilAvailable = new AutoResetEvent(false);
for (int i = 0; i < 5; ++i)
{
var obj = new MyType();
Add(obj);
}
}
public MyType Get()
{
_blockUntilAvailable.WatiOne();
lock (_internalStack)
{
var obj = _internalStack.Pop();
if (_internalStack.Count > 0)
{
_blockUntilAvailable.Set();
}
return obj;
}
}
public void Add(MyType obj)
{
lock (_internalStack)
{
_internalStack.Push(obj);
_blockUntilAvailable.Set();
}
}
}
AutoResetEvent WaitOne(). , , . -.
EDIT: Silverlight.