views:

40

answers:

2

Ok I am using the HttpWebRequest BeginGetResponse and I pass in the async callback function, now I want to pass in a variable/context as well that I want to my callback function to get. How do I do this. I am fairly new to the C#/.Net/Silverlight world.

 HttpWebRequest absRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(urlToFetch));
        absRequest.BeginGetResponse(new AsyncCallback(onABSFetchComplete), absRequest);

here my objective is in the above call I want to pass a variable and I want my callback to get called with that variable. thanks!

+1  A: 

The simplest way to do this is to use a lambda expression. Something like this:

absRequest.BeginGetResponse(result => OnFetchComplete(result, foo, absRequest),
                            null);

where OnFetchComplete now has the signature you really want (with the extra parameters - in this case one corresponding to foo) rather than just an IASyncResult. You no longer need to give absRequest as the "context" for the IAsyncResult, as you're capturing it in the lambda expression.

If you're not familiar with lambda expressions though, you should really take time to get to grips with them though - not just for this, but for LINQ and all kinds of other purposes.

Jon Skeet
thanks a lot that solution worked and I sure will read up on this.
gforg
How can i achieve the functionality in C#.NET alone without ASP.NET (like httpWebRequest...etc.)?
sukumar
@sukumar: HttpWebRequest has BeginGetResponse already. That's not part of ASP.NET.
Jon Skeet
A: 

You could use an anonymous delegate and capture in its implementation the variable you want to use

vc 74