C#同步等待/轮询方法 [英] C# Synchronize Wait / Poll methods
问题描述
我有一个公开两种方法的类:
I have a class that exposes two methods:
-GetObject
获取单个对象,如果没有,则返回null.
Gets a single object, or returns null if there are none.
-WaitForObject
获取单个对象,或等到它们成为一个对象.
Gets a single object, or waits until their is one.
示例实现:
class MyClass
{
MyStack stack;
public object GetObject()
{
return stack.Pop();
}
public object WaitForObject()
{
object returnValue;
while (returnValue == null)
returnValue = stack.Pop()
return returnValue
}
}
假设MyStack
是线程安全的,如何使MyClass
线程安全?即
With the assumption that MyStack
is thread safe, how can I make MyClass
thread safe? I.e.
-GetObject
永不阻塞
-Thread
执行WaitForObject
应该将所有新对象添加到堆栈中,而不是GetObject
.
- GetObject
should never block
- Thread
doing WaitForObject
should get any new objects added to the stack instead of GetObject
.
要获得加分,用户如何将对象添加到堆栈中,以通知任何侦听器新对象可用? (无需轮询)
For bonus points, how can users adding objects to the stack notify any listeners that a new object is available? (eliminating the need for polling)
推荐答案
我认为您可以使用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);
}
}
}
这篇关于C#同步等待/轮询方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!