Fun With WCF and Bi-directional (Duplex) actions

A rather interesting situation arose recently when working on a WCF (Windows Communication Foundation) related app. A certain application I work on uses WCF for it’s client/server communications. Recently, that has involved some bi-directional (duplex) operations. For those who haven’t used WCF or have no idea what I’m talking about – basically the client application sends a message to the server. The server then sends a message out, either back to the client or to all the clients. The server doesn’t initially have to receive anything from the client. If it wanted to, it could randomly send messages to the clients without having the initial “request” from the client. In this way, it is a bit different than the classic “request->response” model that is normally used in with WCF.

Anyway, back to the interesting bits. The part of the application that I was working on was to allow the client application to send messages to the other client apps that are currently logged in. For some odd reason, the client application could send messages just fine to other clients, but when it tried sending itself a message, the whole client app would keel over and die. No exception was thrown. It took me a little while to figure out what was happening. What was happening is the client would send a request to the server (ie: “Hey server, send this message to these people!”). The server would then attempt to send messages to the list of people that it was supposed to – however – when the server tried to send a message to the client who started the whole thing, it would more or less hang the client. This was because it was creating a deadlock situation. The client who had send the message was waiting to hear back from the server, however, the server was waiting to hear back from the client (who wouldn’t respond, because it was busy waitng to hear back from the server).

To fix this problem, what I ended up doing was firing off the initial “Hey server, send this message to these people” process on a separate thread. This would allow the main thread of the application to continue on, and respond to the server when the server sent it a message.

The whole thing was pretty interesting to figure out, especially how to handle things on multiple threads. It really makes me have a greater appreciation for those crazy multi-threaded game engines. That, and it makes me want to try writing a multi-threaded game engine in .Net.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s