我正在尝试连接一个 AsyncController,以便当用户在订单页面上单击保存订单时,查看同一订单的所有用户都应该收到订单已更改的通知。我实现这一点的方法是在订单页面上执行长轮询 ajax 请求,但是如何制作可扩展的 AsyncController 来处理这个问题对我来说并不明显。
所以这就是我到目前为止所拥有的,ID 是指示已更改或轮询更改的订单的 ID。
public class MessageController : AsyncController
{
static readonly ConcurrentDictionary<int, AutoResetEvent> Events = new ConcurrentDictionary<int, AutoResetEvent>();
public ActionResult Signal(int id)
{
AutoResetEvent @event;
if (Events.TryGetValue(id, out @event))
@event.Set();
return Content("Signal");
}
public void WaitAsync(int id)
{
Events.TryAdd(id, new AutoResetEvent(false));
// TODO: This "works", but I should probably not block this thread.
Events[id].WaitOne();
}
public ActionResult WaitCompleted()
{
return Content("WaitCompleted");
}
}
我看过How to do long-polling AJAX requests in ASP.NET MVC? . 我试图了解有关此代码的所有详细信息,但据我了解此代码它阻塞了线程池中的每个工作线程,据我所知,这最终会导致线程饥饿。
那么,我应该如何以一种很好的、可扩展的方式实现它呢?请记住,我不想再使用任何第三方组件,我想很好地了解如何正确实施此方案。