views:

221

answers:

2

Like the title says:

My web service method call looks like

proxy.BeginGetWhatever(int param)
{
}

Lets assume the handler registered with this call is

private void GetWhateverCompleted(object sender, GetWhateverEventArgs e)
{
    //HERE
}

How do I get access to the parameter param in the handler? (e.Result will return whatever the web service call is supposed to fetch. I am interested in making param available as well)

A: 

Your web method would have to return it somehow. Let's say your webmethod is to return the original parameter and some other data back to the caller, here's the web method signature:

CustomReturnClass GetWhatever(int param);

And the definition of CustomReturnClass defined in the web service.

public class CustomReturnClass
{
   public int OrigParameter { get; set; }
   public object OtherStuff { get; set; }
}

Then in your callback (traditional style) you would have:

private void GetWhateverCompleted(IAsynchResult res)
{
    CustomReturnClass retVal = (CustomReturnClass)res.EndGetWhatever(res);
    int origParam = retVal.OrigParameter;
}

It looks, however, like you're using WCF, so it would be more like this:

private void GetWhateverCompleted(object sender, GetWhateverEventArgs e)
{
    CustomReturnClass retVal = e.Result;
    int origParam = retVal.OrigParameter;
}
Steve Danner
I guess, to clarify, the challenge is to return whatever the web service method returns + the parameter so I can make use of it in the handler. How could I make that work?
Rire1979
OK, I think I might have a better understanding this time. Check my edits to see if that helps.
Steve Danner
A: 

Each async method generated for a WCF proxy will have an overload that takes a userState parameter. For example, if you have a GetCustomerByID method, you'll see two overloads:

public void GetCustomerByIDAsync(Guid customerID) { ... }
public void GetCustomerByIDAsync(Guid customerID, object userState { ... }

You can put whatever you want in userState and it will be sent back in the completion event. So if you just want the original customerID back, in the above case:

public void BeginGetCustomerByID(Guid customerID)
{
    // Second instance of customerID is userState
    service.GetCustomerByIDAsync(customerID, customerID);
}

private void service_GetCustomerByIDCompleted(object sender,
    GetCustomerByIDCompletedEventArgs e)
{
    Guid customerID = (Guid)e.UserState;
    // Do something with e.Error or e.Result here
}

You can put anything you want in userState, so if the method takes several parameters, you can put them all into a custom class and pass the class as the state.

Aaronaught