在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,但我不能这样做。请告诉我怎么做?
答案 0 :(得分: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;
}