1

在 Windows 8 中,我尝试从 URL 获取 html 源代码:

private void loadingDatafromWeb(string URL)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
    request.BeginGetResponse(new AsyncCallback(ReadCallbackLoadingData),request);
}

和:

private void ReadCallbackLoadingData(IAsyncResult asynchronousResult)
{
    string myPageSource;
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
    HttpWebResponse response =   (HttpWebResponse)request.EndGetResponse(asynchronousResult);
    using (StreamReader myWebSource = new StreamReader(response.GetResponseStream()))
    {
        myPageSource = myWebSource.ReadToEnd();
    }

我想在函数 loadingDatafromWeb 中获取字符串 myPageSource,但我做不到。请告诉我怎么做?

4

1 回答 1

0

您可以使用新的 .Net 4.5 功能并使用await关键字调用:

private void loadingDatafromWeb(string URL)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
    string html = await ReadData(new Uri(request));
}

你的辅助方法是:

private async Task<string> ReadData(Uri uri)
{
     string result;

     // Get your response synchronously (do not forget to enscope WebResponse
     // and other Streams inside 'usings').

     return result;
}
于 2012-11-08T10:14:13.460 回答