【问题标题】:Broker that makes async calls with a synchronous facade in c#在 C# 中使用同步外观进行异步调用的代理
【发布时间】:2019-01-03 15:59:48
【问题描述】:

我想通过 websocket 进行多次调用,并为每个调用获取结果。

_svc.DoAthing(param) =broker calls=> ws.SendMessage(doathingmessage(ticket))
                     <=broker returns= ws.Onmessage+=handler=>(doathingresult(ticket))

什么是让经纪人这样的最佳方式

  1. 此异步请求显示为同步
  2. 代理可以处理数百个请求
  3. 客户端不应不断轮询其线程,它应该阻塞或等待。

不确定是否有一堆线程轮询已完成的票证是最好的方法。

【问题讨论】:

    标签: c# multithreading threadpool messagebroker websocket-sharp


    【解决方案1】:

    我认为这会很好,但我仍在寻找更优雅的解决方案

        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();
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 2014-01-28
      • 2017-02-15
      相关资源
      最近更新 更多