WCF Trip - What Happens To BeginInvoke

|

Recently I came across Nicholas Allen's blog post talking about how BeginInvoke breaks when used against proxies generated by WCF client runtime, specifically the ChannelFactory. and his conclusion to the misbehaviour exposed by BeginInvoke right here is something like this (quoted from the original article):

The problem is that BeginInvoke knows about and only works with specific types of proxy objects, which do not include the proxy objects generated by ChannelFactory.

Actually Nicholas Allen's reasoning here is kinda like a "technical correct but lack of detailed explanation" statement, if you write something like the following, no one can imagine that you are actually doing something wrong:

String uri = "net.tcp://localhost:2222/Services";
ChannelFactory<IEchoService> factory = new ChannelFactory<IEchoService>(new NetTcpBinding(), uri);
IEchoService proxy = factory.CreateChannel();
EchoDelegate d = new EchoDelegate(proxy.Echo);
IAsyncResult result = d.BeginInvoke("foo", new AsyncCallback(Callback), null);

So what really happens here?

Let's first add some piece of code into the original testing code to check some of presumptions I make on the proxy generated by ChannelFactory:

Console.WriteLine(System.Runtime.Remoting.RemotingServices.IsTransparentProxy(proxy));
Console.WriteLine(System.Runtime.Remoting.RemotingServices.GetRealProxy(proxy).GetType());
Console.WriteLine(result.IsCompleted);

If running the modified code, you will find some of the interesting bits:

  1. The proxy generated by WCF client runtime aka ChannelFactory is actually a TransparentProxy;
  2. The RealProxy paired with this TransparentProxy is a System.ServiceModel.Channels.ServiceChannelProxy implementation;
  3. When beginInvoking against a proxy generated by ChannelFactory, the call is performed as ordinary synchronous method invocation.

So what's the happening here? How does WCF relate to the remoting architecture such as TransparentProxy and RealProxy metaphors? and specifically why does BeginInvoke break here?

To answer those questions, let's first take on the first question, and digg into it, I've spent several hours to examine the implementation of WCF ChannelFactory implementation, one of the greatest discovery I find is that before kicking off the channel stack to process the service request, WCF client runtime will actually intercept every WCF service call by injecting a TransparentProxy and ServiceChannelProxy between WCF service call site and underlying the channel stack. The reason WCF implements the client runtime the way it is is that WCF needs to differ between normal method invocation and WCF service invocation on service proxy objects. how about if you call GetType() on the proxy generated by the ChannelFactory, what type do you expect the GetType() method will return? If you write the code to test, you will get stunned by realizing that GetType() will actually return IEchoService, WTF? How does GetType() method return the interface type object rather than the concrete type object? Actually, WCF has been intercepted the call to GetType(), and revamped it to return the underlying proxied type, thus hiding the real proxy implementation for IEchoService. Another reason WCF intercepts every method call is to differ between synchronous service calls and asynchronous service calls. Imagine you have a WCF service contract like this:

[ServiceContract]
public interface IEchoService
{
    [OperationContract]
    String Echo(String text);
}

   If you run the svcutil.exe tool to generate client side proxy implementation for async call just as Nicholas Allen suggested in his original article:

   svcutil /language:C# /config:App.config /async net.tcp://localhost:2222/Services

   you will get something like this:

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="IEchoService")]
public interface IEchoService
{
   
    [System.ServiceModel.OperationContract]
    string Echo(string text);
   
    [System.ServiceModel.OperationContract]
    System.IAsyncResult BeginEcho(string text, System.AsyncCallback callback, object asyncState);
   
    string EndEcho(System.IAsyncResult result);
}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public interface IEchoServiceChannel : IEchoService, System.ServiceModel.IClientChannel
{
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class EchoServiceClient : System.ServiceModel.ClientBase<IEchoService>, IEchoService
{
   
    public EchoServiceClient()
    {
    }
   
    public EchoServiceClient(string endpointConfigurationName) : base(endpointConfigurationName)
    {
    }
   
    public EchoServiceClient(string endpointConfigurationName, string remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
    {
    }
   
    public EchoServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress)
    {
    }
   
    public EchoServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress    remoteAddress) : base(binding, remoteAddress)
    {
    }
   
    public string Echo(string text)
    {
        return base.Channel.Echo(text);
    }
   
    public System.IAsyncResult BeginEcho(string text, System.AsyncCallback callback, object asyncState)
    {
        return base.Channel.BeginEcho(text, callback, asyncState);
    }
   
    public string EndEcho(System.IAsyncResult result)
    {
        return base.Channel.EndEcho(result);
    }
}

From the above code, we find that WCF follows .NET's asynchronous method invocation pattern quite closely by pairing each service operation call XX with a BeginXX and EndXX async call implementation. the code shown above is really clear and standard, but how does it work out actually? How does a BeginXX call will be performed asynchronously? and how does a EndXX kicks in here to finalize the asynchronous service invocation?

In order to let the BeginXX and EndXX work as their signature indicate, WCF actually needs to know which service invocation is going to be performed through BeginXX or EndXX calls, to put it another way, WCF needs to know if the BeginXX or EndXX has been called, so it will perform its underlying plumbing to do the magic, in order to get those invocation infomation, WCF needs to have the capability to fine-grained control over the invocation of the service operations exposed by the service contracts. Since TransparentProxy and RealProxy mechanism which is heavily used by the .NET remoting has already haven this capability directly built into the CLR, WCF can leverage this infrastructure to intercept the method calls, and perform its underlying async plumbing at the channel level according to method you are going to invoke.

Right now, I am almost finishing answering the first question - How does WCF relate to the remoting architecture such as TransparentProxy and RealProxy metaphors? but how about the second question I raised myself, why does BeginInvoke break when all the TP and RP plumbing is in place? This question is much trickier than it seems to be, after a bit of research on the default implementation of TP and RP mechanism used by .NET remoting using both  .NET reflector and the rotor 2.0 implementation of CLR, I finally figure out that for the current implementation of TP and RP mechanism, it only supports asynchronous call when the default RemotingProxy is in place, since the ServiceChannelProxy is WCF's own implementation, it gets ignored by the BeginInvoke mechanism, and the BeginInvoke call against WCF's proxies will be performed synchronously.

Up until now, all the puzzles has been demystified. BeginInvoke is probably one of the most confusing APIs in the .NET framework as this article and my previous article demonstrates:)

1 comments:

Vincent-Philippe Lauzon said...

Very interesting article!

I was probing around with a POC to do async on a ChannelFactory created proxy, doing some reflection and looking for some litterature, I bumped into this blog post.

So, tell me, since you went quite further, how would you implement real async (i.e. letting .NET use IO ports and freeing threads) on a ChannelFactory create proxy? Is that physically possible?