[英]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.