C# 同步等待/轮询方法
我有一个公开两个方法的类:
- GetObject
获取单个对象,如果没有则返回 null。
- WaitForObject
获取单个对象,或等待直到它们成为一个对象。
示例实现:
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
线程安全?即
- GetObject
永远不应该阻塞 - Thread
执行 WaitForObject
应该将任何新对象添加到堆栈中,而不是 GetObject
。
为了获得奖励积分,向堆栈添加对象的用户如何通知任何侦听器有新对象可用? (消除了轮询的需要)
I have a class that exposes two methods:
- GetObject
Gets a single object, or returns null if there are none.
- WaitForObject
Gets a single object, or waits until their is one.
An example implementation:
class MyClass
{
MyStack stack;
public object GetObject()
{
return stack.Pop();
}
public object WaitForObject()
{
object returnValue;
while (returnValue == null)
returnValue = stack.Pop()
return returnValue
}
}
With the assumption that MyStack
is thread safe, how can I make MyClass
thread safe? I.e.
- 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果
MyStack
保证是线程安全的,那么MyClass
也是线程安全的。在这两种方法中,您仅使用局部变量,因此这些方法是可重入的。目前,用户无法将对象添加到堆栈中,因为
stack
字段在类外部不可见。另外,我没有从您的代码中看到侦听器如何订阅任何事件,以便在添加对象时通知他们。因此,您可以有一个允许将元素添加到堆栈的方法以及在这种情况下将触发的事件。If
MyStack
is guaranteed to be thread safe thenMyClass
is also thread safe. In the two methods you are using only local variables so the methods are reentrant.Currently users cannot add objects to the stack because the
stack
field is not visible outside the class. Also I don't see from your code how do listeners will subscribe to any events so that they are notified if an object is added. So you could have a method allowing to add elements to the stack and an event that will be triggered in this case.我认为您可以使用监视器功能实现一切。只是一个草图
I think that you can achieve everything with Monitor functionality. just a sketch
轮询通常涉及某种形式的睡眠 - 您的示例中的循环将是一个紧密的循环,会一直限制头部。添加 Thread.Sleep(100) 调用或其他一些合理的值,以便随时间轮询。
另一种等待方法是注册回调,或者让堆栈公开阻塞
Pop
方法,无论哪种方式,这些都将在示例中的Stack
类中实现。额外答案:您的类需要公开一个事件,当它们将对象添加到堆栈时,它将触发该事件。
Polling usually involves some form of sleep - the loop in your example would be a tight loop that would throttle the thead all the time. Add a
Thread.Sleep(100)
call, or some other sensible value, to poll over time.The other way to wait would be to register a callback, or have the stack expose a blocking
Pop
method, either way, these would be implemented in theStack
class in your example.Bonus Answer: Your class would need to expose an event, when they add an object to the stack, it would fire this event.