Webclient 的 DownloadStringCompleted 事件处理程序未触发 [英] Webclient's DownloadStringCompleted event handler not firing

查看:26
本文介绍了Webclient 的 DownloadStringCompleted 事件处理程序未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 Silverlight 仪表板,显示多个设备和网站的状态(启动、关闭等).我正在尝试使用 WebClient 类连接到网站并查看它是否已启动.但是 DownloadStringCompleted 事件处理程序永远不会被触发.这是一个与这篇文章非常相似的问题.

I am creating a Silverlight dashboard showing the status of several devices and websites (up, down, etc). I am trying to use the WebClient class to connect to a website and see if it's up. But the DownloadStringCompleted event handler never gets fired. 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?

推荐答案

您试图将异步方法调用诱导为同步方法 - 这将不起作用,因为该方法将在 Web 客户端的完成回调具有机会执行.

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.

使用 Silverlight,您应该拥抱异步.一种方法是传入一个继续委托,该委托在下载字符串后运行您想要执行的代码.

With Silverlight you should embrace async. One way to do this is pass in a continuation delegate that runs the code you want executed once the string has been downloaded.

这篇关于Webclient 的 DownloadStringCompleted 事件处理程序未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆