且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#同步等待/轮询方法

更新时间:2022-05-10 21:20:32

我认为您可以使用Monitor功能实现一切.只是一个草图

I think that you can achieve everything with Monitor functionality. just a sketch

class MyClass
{
    private Stack<object> stack = new Stack<object>();
    public object GetObject()
    {
        lock(stack)
        {
            return stack.Count != 0 ? stack.Pop() : null;
        }
    }
    public object WaitForObject()
    {
        lock (stack)
        {
            if (stack.Count == 0)
            {
                // wait until PutObject is called
                Monitor.Wait(stack);
            }

            return stack.Pop();
        }
    }

    public void PutObject(object obj)
    {
        lock (stack)
        {
            stack.Push(obj);
            // notify one thread blocked by WaitForObject call
            Monitor.Pulse(obj);
        }
    }
}