Webclient's DownloadStringCompleted event handler not firing

梦想与她 提交于 2019-12-13 03:54:16

问题


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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/10521232/webclients-downloadstringcompleted-event-handler-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!