开发者

How to retrieve parameter passed to WebService Async method in the handler of the Completed event

开发者 https://www.devze.com 2022-12-19 19:01 出处:网络
Like the tit开发者_JS百科le says: My web service method call looks like proxy.BeginGetWhatever(int param)

Like the tit开发者_JS百科le 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)


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.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消