Async in the wild: WCF

Spread the love

WCF (client) is open source. An interesting side effect of this development is the opportunity for async enthusiasts to pore over some production-ready async code. Since WCF was released even before .NET 3.5, it has several clever patterns for sensibly dealing with the legacy async programming model (IAsyncResult).

For example, let’s take a look at ChainedAsyncResult. This is an extension on top of the base AsyncResult (itself a more or less textbook example of APM with a few WCF-isms like fatal exception handling). As the name suggests, it chains two successive asynchronous operations together in a simple and repeatable way. An example use case is contained within ServiceChannelFactory+TypedServiceChannelFactory:

protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
    return new ChainedAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose,
    _innerChannelFactory.BeginClose, _innerChannelFactory.EndClose);
}

The close operation on the typed channel factory consists of closing the base factory followed by the inner factory. Without the luxury of ContinueWith, this could be a relatively complex and error-prone operation. But ChainedAsyncResult encapsulates the complexity and takes care of the many “gotchas” including proper synchronous completion handling (i.e. exit the callback and let the original caller handle completion to avoid stack dives) and timeout behavior (using the oft-employed TimeoutHelper).

The open source portion of WCF is relatively thin thus far. Nonetheless, there are many interesting async gems already there for the curious. Take a look!

Leave a Reply

Your email address will not be published. Required fields are marked *