C# Webclient的DownloadStringCompleted事件处理程序未启动

C# Webclient的DownloadStringCompleted事件处理程序未启动,c#,.net,silverlight,webclient,C#,.net,Silverlight,Webclient,我正在创建一个Silverlight仪表板,其中显示了几个设备和网站的状态,如向上、向下等。我正在尝试使用WebClient类连接到一个网站,并查看它是否向上。但DownloadStringCompleted事件处理程序从未被激发。这是一个非常类似的问题 有人看到这里的问题了吗?您试图将异步方法调用诱使到同步方法中-这不会起作用,因为该方法将在web客户端的完成回调有机会执行之前返回 使用Silverlight,您应该接受异步。一种方法是传入一个continuation委托,该委托在下载字符串后

我正在创建一个Silverlight仪表板,其中显示了几个设备和网站的状态,如向上、向下等。我正在尝试使用WebClient类连接到一个网站,并查看它是否向上。但DownloadStringCompleted事件处理程序从未被激发。这是一个非常类似的问题


有人看到这里的问题了吗?

您试图将异步方法调用诱使到同步方法中-这不会起作用,因为该方法将在web客户端的完成回调有机会执行之前返回

使用Silverlight,您应该接受异步。一种方法是传入一个continuation委托,该委托在下载字符串后运行您希望执行的代码

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;
}