Web 客户端的 DownloadStringCompleted 事件处理程序从未调用

发布于 2024-12-04 10:44:44 字数 641 浏览 0 评论 0原文

我正在尝试使用 Webclient 发出异步 HTTP GET 请求,但是,注册的回调永远不会被调用。我也尝试过同步,效果很好。我做错了什么?

WebClient asyncWebRequest;
public AsyncWebRequest(Uri url)
{
    asyncWebRequest = new WebClient();
    url = new Uri("http://www.google.com/");
    // string test = asyncWebRequest.DownloadString(url);  // this works
    asyncWebRequest.DownloadStringCompleted += new DownloadStringCompletedEventHandler(asyncWebRequest_DownloadStringCompleted);
    asyncWebRequest.DownloadStringAsync(url);
}

void asyncWebRequest_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    throw new NotImplementedException();
}

I'm trying to make an asynchronous HTTP GET request using Webclient, however, the registered callback never gets called. I've also tried with the sync one, and it worked fine. What am I doing wrong?

WebClient asyncWebRequest;
public AsyncWebRequest(Uri url)
{
    asyncWebRequest = new WebClient();
    url = new Uri("http://www.google.com/");
    // string test = asyncWebRequest.DownloadString(url);  // this works
    asyncWebRequest.DownloadStringCompleted += new DownloadStringCompletedEventHandler(asyncWebRequest_DownloadStringCompleted);
    asyncWebRequest.DownloadStringAsync(url);
}

void asyncWebRequest_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    throw new NotImplementedException();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

帝王念 2024-12-11 10:44:44

也许是因为您在下载完成之前就处理了 WebClient。代码执行不会在 asyncWebRequest.DownloadStringAsync(url); 上停止,并且您将通过关闭 using 语句来处置 WebClient 对象。

尝试在 asyncWebRequest_DownloadStringCompleted 上处置 WebClient

结果

在此处输入图像描述

Maybe because you disposing the WebClient before it finished downloading. The code execution don't stop on asyncWebRequest.DownloadStringAsync(url); and you are disposing the WebClient object by closing the using statement.

try to dispose the WebClient on asyncWebRequest_DownloadStringCompleted.

results

enter image description here

悍妇囚夫 2024-12-11 10:44:44

最简单的解决方案是在 AsyncWebRequest(url) 方法末尾添加 Console.ReadKey() 。这样 asyncWebRequest.DownloadStringAsync(url) 将能够检索数据。

The simpliest solution is to add Console.ReadKey() at the end of AsyncWebRequest(url) method. This way asyncWebRequest.DownloadStringAsync(url) will be able to retrieve data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文