Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 网络客户端';s DownloadStringCompleted事件处理程序从未调用_C#_.net_Webclient - Fatal编程技术网

C# 网络客户端';s DownloadStringCompleted事件处理程序从未调用

C# 网络客户端';s DownloadStringCompleted事件处理程序从未调用,c#,.net,webclient,C#,.net,Webclient,我试图使用Webclient发出一个异步HTTP GET请求,但是,注册的回调从未被调用。我也试过同步的,效果很好。我做错了什么 WebClient asyncWebRequest; public AsyncWebRequest(Uri url) { asyncWebRequest = new WebClient(); url = new Uri("http://www.google.com/"); // string test = asyncWebRequest.Dow

我试图使用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();
}

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

尝试在
asyncWebRequest\u DownloadStringCompleted
上处理
WebClient

结果


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

我已经更新了问题中的代码。它仍然不工作。嗯,是的,问题是我已经将它作为一个控制台应用程序进行了测试,在调用它之前它就退出了。(见对我问题的第一条评论)是的,我看到了。将
Console.ReadLine()
放在
Main
方法的末尾,等待异步调用结束。我猜您是在控制台应用程序中测试这一点,并在下载完成之前退出
Main
?嗯。谢谢,这就是问题所在。