循環中有多個HttpWebRequest?


我必須多次調用web服務(循環)問題是我的代碼總是返回空對象(圖像描述)並且當我單獨測試它(循環外)時它運行不正常它正常工作

這是我的代碼部分

HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(imageCollection[i].ImageTag));

            httpReq.BeginGetResponse(new AsyncCallback((iar) =>
             {
                 try
                 {
                     string strResponse = "";
                     var response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar);

                     Stream stream = response.GetResponseStream();
                     StreamReader reader = new StreamReader(stream);
                     strResponse = reader.ReadToEnd();

                     HtmlDocument htmlDocument = new HtmlDocument();
                     htmlDocument.OptionFixNestedTags = true;
                     htmlDocument.LoadHtml(strResponse);
                     HtmlAgilityPack.HtmlNode titleNode = htmlDocument.DocumentNode.SelectSingleNode("//meta[@property='og:description']");

                     if (titleNode != null)
                     {
                         string desc = titleNode.GetAttributeValue("content", "");
                         imageCollection[i].ImageDescription = desc;
                     }
                 }
                 catch (Exception ex)
                 {
                     throw ex;
                 }

             }), httpReq);

            httpReq.Abort();

一般承認的答案

我從堆棧溢出中的另一個帖子得到了答案,修改了以適應我的解決方案獲取異步HttpWebRequest的響應

我創建了一個名為Request的特定類,將我的邏輯轉換為新的異步,然後等待它

       public Task<string> MakeAsyncRequest()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

            Task<WebResponse> task = Task.Factory.FromAsync(
                request.BeginGetResponse,
                asyncResult => request.EndGetResponse(asyncResult),
                (object)null);

            return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
        }

        private string ReadStreamFromResponse(WebResponse response)
        {
            string desc = "";
            try
            {
           using (Stream responseStream = response.GetResponseStream())
                using (StreamReader sr = new StreamReader(responseStream))
                {
                    //Need to return this response 
                    string strContent = sr.ReadToEnd();
                    HtmlDocument htmlDocument = new HtmlDocument();
                    htmlDocument.OptionFixNestedTags = true;
                    htmlDocument.LoadHtml(strContent);
                    HtmlAgilityPack.HtmlNode titleNode = htmlDocument.DocumentNode.SelectSingleNode("//meta[@property='og:description']");

                    if (titleNode != null)
                    {
                        desc = titleNode.GetAttributeValue("content", "");

                    }
                    imageDesc = desc;
                    return desc;
                }
            }
            catch (Exception ex)
            { return desc; }
        }

        public string imageDesc { get; private set; }

    }

然後我做了一個請求隊列

       public Task<string> MakeAsyncRequest()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

            Task<WebResponse> task = Task.Factory.FromAsync(
                request.BeginGetResponse,
                asyncResult => request.EndGetResponse(asyncResult),
                (object)null);

            return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
        }

        private string ReadStreamFromResponse(WebResponse response)
        {
            string desc = "";
            try
            {
           using (Stream responseStream = response.GetResponseStream())
                using (StreamReader sr = new StreamReader(responseStream))
                {
                    //Need to return this response 
                    string strContent = sr.ReadToEnd();
                    HtmlDocument htmlDocument = new HtmlDocument();
                    htmlDocument.OptionFixNestedTags = true;
                    htmlDocument.LoadHtml(strContent);
                    HtmlAgilityPack.HtmlNode titleNode = htmlDocument.DocumentNode.SelectSingleNode("//meta[@property='og:description']");

                    if (titleNode != null)
                    {
                        desc = titleNode.GetAttributeValue("content", "");

                    }
                    imageDesc = desc;
                    return desc;
                }
            }
            catch (Exception ex)
            { return desc; }
        }

        public string imageDesc { get; private set; }

    }




許可下: CC-BY-SA
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因