Wednesday, September 29, 2010

WCF Fire and Forget Method Not Returning

Here's something that might trip you up if you're using a WCF Fire and Forget method to exit early from a long-running method.


Scenario: You create an operation contract and set the IsOneWay attribute to true. Then you implement the method and let's say it takes thirty seconds to finish.










Then on your client when you call this method you create your proxy inside a using statement because you want to dispose of the proxy after the call (when the 'using' statement exits if all goes well).













And when you run your code, the code finishes immediately and and all is well.


Oh, wait. Your client is hanging. It's taking...thirty seconds to finish, which is about as long as it would take if it were a request/response method.


It turns out, if you step into the client code, your proxy call is returning immediately. What's taking the thirty seconds to complete is the disposal of the proxy. The client can't exit from the using statement until the proxy is disposed of, and the proxy will not dispose of itself until the fire and forget method completes.


So what are your options?
  1. Reuse the proxy and/or keep the proxy alive indefinitely.
  2. Make your method request/response and call it asynchronously instead