gforg
gforg

Reputation: 263

silverlight/wp7: HTTPwebrequest BeginGetResponse lambda expression not working correctly

I am calling the HTTPwebrequest BeginGetResponse within a loop with lambda expression (here the index is incremented each time in the loop).

Tried using both the below approaches, however when OnHTMLFetchComplete is called I only get the final index value and not the intermediate ones.

option1:

  HttpWebRequest itemHtmlRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(itemDetail.Links));
  itemHtmlRequest.BeginGetResponse(result => OnHTMLFetchComplete(result, index, itemHtmlRequest),null);

Option2:

  HttpWebRequest itemHtmlRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(itemDetail.Links));

  itemHtmlRequest.BeginGetResponse(new AsyncCallback(
      result => OnHTMLFetchComplete(result, index, itemHtmlRequest)), null);

Upvotes: 0

Views: 1365

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500515

This is the common problem of capturing a loop variable. The lambda expression captures the index variable, not its value. It's a simple fix though:

for (int index = 0; index < ...; index++)
{
    int indexCopy = index;
    Uri uri = ...;
    HttpWebRequest itemHtmlRequest = WebRequest.CreateHttp(uri);
    itemHtmlRequest.BeginGetResponse(
        result => OnHTMLFetchComplete(result, indexCopy, itemHtmlRequest),null);
}

Here you're capturing indexCopy instead of index - but whereas there's just one index variable, there's a new indexCopy variable on each iteration of the loop. The value of index changes over time, whereas the value of indexCopy doesn't, so you're okay.

Eric Lippert has a great pair of blog posts about this: part 1; part 2.

(Note: there are loads of questions which have a similar answer. However, all the actual questions are different. I personally think it's worth answering each different question, to hopefully make it easier to find similar questions in the future.)

Upvotes: 4

Magnus Johansson
Magnus Johansson

Reputation: 28325

Without seeing the whole code, my guess is that the outer loop iterations have already been completed before any of the async code has received any HTTP response.

Upvotes: 0

Related Questions