How to: Responsive available Wcf duplex communication

爱⌒轻易说出口 提交于 2019-12-06 13:14:43

I have a similar environment (without the dynamic services) and had a very similar issue when client channels faulted. The first solution I came up with was to wrap the callbacks in try/catch statements and remove the offending client if something went wrong but this had issues and didn't look like it would scale at all.

The solution I ended up going with was to use a delegated event handler and to call it using BeginInvoke. If you haven't looked at the CodeProject: WCF/WPF Chat Application (Chatters) solution, I recommend checking it out.

When a user logs in, an event handler is created and added to the main event:

public bool Login() 
{
    ...
    _myEventHandler = new ChatEventHandler(MyEventHandler);
    ChatEvent += _myEventHandler;
    ...
}

Whenever a message needs to be broadcast, the event handlers are called asynchronously:

private void BroadcastMessage(ChatEventArgs e)
{
    ChatEventHandler temp = ChatEvent;
    if (temp != null)
    {
        foreach (ChatEventHandler handler in temp.GetInvocationList())
        {
            handler.BeginInvoke(this, e, new AsyncCallback(EndAsync), null);
        }
    }
}

When the returns come back, the result is handled and if something bad happened the event handler for that channel is removed:

private void EndAsync(IAsyncResult ar)
{
    ChatEventHandler d = null;
    try
    {
        //get the standard System.Runtime.Remoting.Messaging.AsyncResult,and then
        //cast it to the correct delegate type, and do an end invoke
        System.Runtime.Remoting.Messaging.AsyncResult asres = (System.Runtime.Remoting.Messaging.AsyncResult)ar;
        d = ((ChatEventHandler)asres.AsyncDelegate);
        d.EndInvoke(ar);
    }
    catch(Exception ex)
    {
        ChatEvent -= d;
    }
}

The code above is modified (slightly) from the WCF/WPF Chat Application posted by Sacha Barber.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!