问题
I'm stuck with a bit of an annoying problem right now. I've got a Silverlight 4 application (which runs OOB by default). It uses WCF with net.tcp as means of communicating with the server. The client uses a central instance of the wcf client proxy. As long as everything keeps running on the server side, everything's fine.
If i kill the server in the middle of everything, i drown in an avalanche of exceptions on the client side (connection lost, channel faulted etc etc).
Now i'm looking for a way to handle this in a clean and centralized way (if centralized is possible).
The SL app has one central client object sitting in App.cs (public static MyClient Client { get;set;}), which gets initialized on application start.
Any idea how to properly handle any connectivity problems on the client object?
回答1:
You mention that you're using a central instance of the WCF client proxy.
If this is the case, then when a server error occurs, the proxy will go into the Faulted state. To keep things centralized, you could cast the client proxy to an ICommuicationObject
and attach an event handler to the Faulted
event which replaces the faulted proxy, with a new proxy when the event fires.
The usual warnings about thread-safety for centralized access to resources apply!
回答2:
I think i found a workable - though not centralized - solution. Instead of cluttering the code with try/catch blocks, all it seems to need is a null-check for the event.Error property. If something happened to the connection, this property is always not null. The exceptions only get raised if you try to access event.Result.
It may not be the most beautiful solution, but it appears to work so far.
Perhaps there is a more elegant way though...
来源:https://stackoverflow.com/questions/3049515/wcf-net-tcp-server-disconnects-how-to-handle-properly-on-client-side