简体   繁体   中英

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);

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.)

在没有看到整个代码的情况下,我的猜测是在任何异步代码收到任何HTTP响应之前,外循环迭代已经完成。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM