2012-05-09 43 views
0

我正在創建一個顯示多個設備和網站(上,下等)狀態的Silverlight儀表板。我正嘗試使用WebClient類連接到網站,看看它是否已經啓動。但是DownloadStringCompleted事件處理程序永遠不會被解僱。這是與this post非常類似的問題。Webclient的DownloadStringCompleted事件處理程序未觸發

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

有沒有人在這裏看到問題?

回答

0

您試圖將異步方法調用轉換爲同步方法 - 它不會起作用,因爲在Web客戶端的完成回調有機會執行之前該方法將返回。

使用Silverlight,您應該擁抱異步。執行此操作的一種方法是傳入一個繼續代理,該代理運行要在字符串下載完成後執行的代碼。

相關問題