C# - 从 WebResponse 获取响应
本文关键字:获取 响应 WebResponse | 更新日期: 2023-09-27 18:37:28
我正在尝试下载放置在互联网上的RSS提要的XML源代码,但是当我的进程到达WebResponse
语句(第二行波纹管)时,进程停止,接下来什么都没有发生。没有错误,没有例外或类似的东西。我等了几十分钟,仍然没有任何反应。
WebRequest request = WebRequest.Create(source.Url);
WebResponse response = await request.GetResponseAsync(); // at this line it stops
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream);
string xml = readStream.ReadToEnd().Trim();
readStream.Dispose();
response.Dispose();
知道是什么原因造成的吗?
编辑:
public static async Task<string> GetContent(string uri)
{
WebRequest request = WebRequest.Create(url);
using (WebResponse response = await request.GetResponseAsync().ConfigureAwait(false))
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream);
return readStream.ReadToEnd().Trim();
}
}
public async Task<ObservableCollection<Source>> GetArticlesFromSource()
{
sourceDefinitions = await GetSourceDefinitions();
string imageFolderName = "ArticleImages";
string imageFolderPath = localFolder.Path + "''" + imageFolderName;
StorageFolder imageFolder = await localFolder.CreateFolderAsync(imageFolderName, CreationCollisionOption.ReplaceExisting);
foreach (var source in sourceDefinitions)
{
if (source.Selected == "true")
{
ObservableCollection<Article> articlesStep1 = new ObservableCollection<Article>();
/*WebRequest request = WebRequest.Create(source.Url);
WebResponse response = await request.GetResponseAsync();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream);*/
string xml = await GetContent("http://www.honzachalupa.cz/").ConfigureAwait(false);
Debug.WriteLine(xml);
...
您的应用程序几乎可以肯定正在调用调用堆栈中更上方的返回任务Wait
或Result
,这将导致我在我的博客上完整解释的死锁。
要修复它,请找到上游Wait
/Result
调用并将其更改为 await
。换句话说,使用"一路异步"。