简体   繁体   English

silverlight / wp7:HTTPwebrequest BeginGetResponse lambda表达式无法正常工作

[英]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). 我正在用lambda表达式的循环中调用HTTPwebrequest BeginGetResponse(此处,每次循环中索引都会递增)。

Tried using both the below approaches, however when OnHTMLFetchComplete is called I only get the final index value and not the intermediate ones. 使用以下两种方法进行了尝试,但是,当调用OnHTMLFetchComplete时,我只会得到最终的索引值,而不是中间的索引值。

option1: 选项1:

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

Option2: 选项2:

  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. lambda表达式捕获index 变量 ,而不是其值。 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. 在这里,我们撷取indexCopy ,而不是index -但鉴于存在只是一个 index的变量,有一个新的indexCopy在每次循环迭代变量。 The value of index changes over time, whereas the value of indexCopy doesn't, so you're okay. index的值随时间变化,而indexCopy的值不随时间变化,所以您可以。

Eric Lippert has a great pair of blog posts about this: part 1 ; 埃里克·利珀特(Eric Lippert)在这方面有很多博客文章: 第1部分 part 2 . 第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响应之前,外循环迭代已经完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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