簡體   English   中英

使用C#中的同步門面進行異步調用的代理

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

什么是使經紀人這樣的最佳方法

  1. 此異步請求顯示為同步
  2. 經紀人可以處理數百個請求
  3. 客戶端不應一直在其線程上進行輪詢,而應阻塞或等待。

不確定是否有一堆線程完成票證輪詢是最好的方法。

我認為這會很好,但仍在尋找更優雅的解決方案

    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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM