views:

247

answers:

1

I have a WCF client (C#) which is communicating with a WCF server. This clients are doing calls asynchronously. I'm wondering whether the following is a good or bad idea:

When calling the asynchronous operation from my WCF client, I set the object asyncState variable to the proxy object. In my callback function, I extract the proxy object from the AsyncState value and call .EndFunction on it.

Example:

public void Login()
{
   Client client = CreateWCFProxy();
   client.BeginLogin(user, pass, OnLoginCompleted, client);
}

public void OnLoginCompleted(IAsyncResult result)
{
   Client client = result.AsyncState as Client;
   LoginResult loginResult = client.EndLogin(result);
}

I could store the Client as a class member, but if I'm doing many simultaneous asynchronous calls that may get complicated. (For example if the proxy dies when I'm doing one async call, I need to create a new proxy. But I still need the old proxy to be able to call .EndFunction on other outstanding async calls.

+2  A: 

That should work just fine. The alternative is to use a lambda expression or an anonymous delegate so you can use the same local variable in your completed code.

An example using a lambda expression

client.BeginLogin(user, pass,
    ar =>
    {
        LoginResult result = client.EndLogin(ar);
        Console.WriteLine(result);
    }, null);
Maurice
Hmm, you mean I should pass that rather than "OnLoginCompleted"?
Nitramk
I added some example code to the answer.
Maurice
I'm stupid not to think about that myself. Thanks.
Nitramk