, , , , ThreadPool.RegisterWaitForSingleObject.
public class ConcurrentLookup<TKey, TValue>
{
private readonly Dictionary<TKey, List<TValue>> _lookup = new Dictionary<TKey, List<TValue>>();
public void Add(TKey key, TValue value)
{
lock (_lookup)
{
if (!_lookup.ContainsKey(key))
_lookup.Add(key, new List<TValue>());
_lookup[key].Add(value);
}
}
public List<TValue> Remove(TKey key)
{
lock (_lookup)
{
if (!_lookup.ContainsKey(key))
return new List<TValue>();
var values = _lookup[key];
_lookup.Remove(key);
return values;
}
}
}
[SessionState(SessionStateBehavior.Disabled)]
public class MessageController : AsyncController
{
static readonly ConcurrentLookup<int, ManualResetEvent> Events = new ConcurrentLookup<int, ManualResetEvent>();
public ActionResult Signal(int id)
{
foreach (var @event in Events.Remove(id))
@event.Set();
return Content("Signal " + id);
}
public void WaitAsync(int id)
{
AsyncManager.OutstandingOperations.Increment();
var @event = new ManualResetEvent(false);
Events.Add(id, @event);
RegisteredWaitHandle handle = null;
handle = ThreadPool.RegisterWaitForSingleObject(@event, (state, timeout) =>
{
handle.Unregister(@event);
@event.Dispose();
AsyncManager.Parameters["id"] = id;
AsyncManager.Parameters["timeout"] = timeout;
AsyncManager.OutstandingOperations.Decrement();
}, null, new TimeSpan(0, 2, 0), false);
}
public ActionResult WaitCompleted(int id, bool timeout)
{
return Content("WaitCompleted " + id + " " + (timeout? "Timeout" : "Signaled"));
}
}