[英]Broker that makes async calls with a synchronous facade in c#
我想在一个websocket上打很多电话,并得到每个电话的结果。
即
_svc.DoAthing(param) =broker calls=> ws.SendMessage(doathingmessage(ticket))
<=broker returns= ws.Onmessage+=handler=>(doathingresult(ticket))
什么是使经纪人这样的最佳方法
不确定是否有一堆线程完成票证轮询是最好的方法。
我认为这会很好,但仍在寻找更优雅的解决方案
private ConcurrentDictionary<Guid, ManualResetEvent> _waitingClients = new ConcurrentDictionary<Guid, ManualResetEvent>();
private ConcurrentDictionary<Guid, byte[]> _hostResponses = new ConcurrentDictionary<Guid, byte[]>();
public TEventResult SendCommand<TEventResult>(ICommand cmd)
{
var mre = new ManualResetEvent(false);
var s = _serialize(cmd);
if(_waitingClients.TryAdd(cmd.Ticket, mre))
{
if (!_sendDownPipe(s))
{
_waitingClients.TryRemove(cmd.Ticket, out mre);
throw new Exception("Could not get Response");
}
}
mre.WaitOne();//todo timeout
byte[] resp;
if(_hostResponses.TryRemove(cmd.Ticket, out resp))
{
var o = _deserialize<TEventResult>(resp);
return o;
}
throw new Exception("Could not get response!");
}
private void _eventRecieved(byte[] s)
{
var evt = _deserialize<IEvent>(s);
if(_hostResponses.TryAdd(evt.Ticket, s))
{
ManualResetEvent mre;
if(_waitingClients.TryRemove(evt.Ticket, out mre))
{
mre.Set();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.