[英]Webclient's DownloadStringCompleted event handler not firing
I am creating a Silverlight dashboard showing the status of several devices and websites (up, down, etc). 我正在创建一个Silverlight仪表板,其中显示了多个设备和网站(上,下等)的状态。 I am trying to use the WebClient class to connect to a website and see if it's up.
我正在尝试使用WebClient类连接到网站,然后查看它是否启动。 But the DownloadStringCompleted event handler never gets fired.
但是DownloadStringCompleted事件处理程序永远不会被触发。 This is a very similar issue to this post .
这是与此帖子非常相似的问题。
public void LoadPortalStatus(Action<IEnumerable<ChartModel>> success, Action<Exception> fail)
{
List<NetworkPortalStatusModel> pingedItems = new List<NetworkPortalStatusModel>();
// Add the status for the portal
BitmapImage bi = IsPortalActive()
? (new BitmapImage(new Uri("led_green_black-100x100.png", UriKind.Relative)))
: (new BitmapImage(new Uri("led_red_black-100x100.png", UriKind.Relative)));
NetworkPortalStatusModel nsm = new NetworkPortalStatusModel
{
Unit = "Portal",
StatusIndicator = new Image { Width = 100, Height = 100, Source = bi }
};
pingedItems.Add(nsm);
// Send back to the UI thread
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(_delagateSuccess, new object[] { pingedItems });
}
private bool IsPortalActive()
{
bool IsActive = false;
WebClient wc = new WebClient();
wc.DownloadStringCompleted += (s, e) =>
{
if (e.Cancelled)
{
_delagateFail(new Exception("WebClient page download cancelled"));
}
else if (e.Error != null)
{
_delagateFail(e.Error);
}
else
{
_portalHtmlResponse = e.Result;
if (_portalHtmlResponse.Contains("Somerville, Ma"))
{
IsActive = true;
}
}
};
wc.DownloadStringAsync(new Uri("https://portal.nbic.com/monitor.aspx"));
return IsActive;
}
Does anyone see the problem here? 有人在这里看到问题吗?
You trying to coax an asynchronous method call into a synchronous method - it's not going to work since the method will return before the completion callback of the web client has a chance to execute. 您试图将异步方法调用哄骗为同步方法-这将无法工作,因为该方法将在Web客户端的完成回调有机会执行之前返回。
With Silverlight you should embrace async. 使用Silverlight,您应该拥抱异步。 One way to do this is pass in a continuation delegate that runs the code you want executed once the string has been downloaded.
一种实现方法是传递一个连续委托,该委托在字符串下载后运行您要执行的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.