2014-01-06 54 views
0

加載的URL,我開始與微軟的這個例子中的Windows Phone編程: http://code.msdn.microsoft.com/wpapps/Hybrid-Web-App-75b7ef74/view/SourceCode加載URL和瀏覽器同步Web客戶端的HttpRequest

該應用程序只顯示在瀏覽器並加載一個URL。

現在我想直接從.txt文件加載其他URL。 例如:http://www.test.de/appurl.txt然後我想在Windows Phone應用程序中加載URL。 - >例如:http://anotherserver.de/index.html?mobileApp

我的問題是,URL必須加載同步而不是異步。我執行AutoResetEvent,但它不工作...

希望有人能幫助我,thx!

這裏是我的代碼:

public partial class MainPage : PhoneApplicationPage 
    { 
     // URL zur WebApp 
     // TODO: URL muss aus diesem TEXT-File ausgelesen werden! 
     private string _appURL = "http://www.test.de/appurl.txt"; 

     public string _homeURL = ""; 
     //private string _homeURL = "http://anotherserver.de/index.html?mobileApp"; 

     // URL zur Registrierung von Angeboten 
     private string _registrationURL = "http://anotherserver.de/index.html?bereich=registrierung&mobileApp"; 

     // Secondary tile data 
     //private Uri _currentURL; 
     //private Uri _tileImageURL; 
     //private string _pageTitle = "Shop "; 

     // Serialize URL into IsoStorage on deactivation for Fast App Resume 
     private Uri _deactivatedURL; 
     private IsolatedStorageSettings _userSettings = IsolatedStorageSettings.ApplicationSettings; 

     // To indicate when we're navigating to a new page. 
     private ProgressIndicator _progressIndicator; 


     // Constructor 
     public MainPage() 
     { 
      InitializeComponent(); 
      //Read the URL from a txt file and set the _homeURL 
      ReadFile(_appURL); 

      // Setup the progress indicator 
      _progressIndicator = new ProgressIndicator(); 
      _progressIndicator.IsIndeterminate = true; 
      _progressIndicator.IsVisible = false; 
      SystemTray.SetProgressIndicator(this, _progressIndicator); 

      // Event handler for the hardware back key 
      BackKeyPress += MainPage_BackKeyPress; 

      // Fast app resume events 
      PhoneApplicationService.Current.Deactivated += Current_Deactivated; 
      PhoneApplicationService.Current.Closing += Current_Closing; 
     } 


     //AutoResetEvent are = new AutoResetEvent(false); 

     public void ReadFile(string address) 
     { 

      var webClient = new WebClient(); 
      webClient.OpenReadAsync(new Uri(address)); 
      webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted); 

      // lock the thread until web call is completed 
      //are.WaitOne(); 

      //finally call the NotifyComplete method to end the background agent 
      //NotifyComplete(); 
     } 


     void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) 
     { 
      try 
      { 
       using (var reader = new StreamReader(e.Result)) 
       { 
        string downloaded = reader.ReadToEnd(); 
        Debug.WriteLine("downloaded= " + downloaded); 
        _homeURL = downloaded; 
        //work = false; 
       } 
      } 
      catch 
      { 
       Debug.WriteLine("Please check your data connection"); 
       MessageBox.Show("Please check your data connection"); 
      } 

       //signals locked thread that can now proceed 
       //are.Set(); 
     } 

     #region App Navigation Events 

     protected override void OnNavigatedTo(NavigationEventArgs e) 
     { 
      base.OnNavigatedTo(e); 

      // Browser event handlers 
      Browser.Navigating += Browser_Navigating; 
      Browser.Navigated += Browser_Navigated; 
      Browser.NavigationFailed += Browser_NavigationFailed; 

      Browser.IsScriptEnabled = true; 

      // Try to get the URL stored for fast app resume. 
      try 
      { 
       _deactivatedURL = (Uri)(_userSettings["deactivatedURL"]); 
      } 
      catch (System.Collections.Generic.KeyNotFoundException keyNotFound) 
      { 
       Debug.WriteLine(keyNotFound.Message); 
      } 

      // Were we started from a pinned tile? 
      if (NavigationContext.QueryString.ContainsKey("StartURL")) 
      { 
       // Navigate to the pinned page. 
       Browser.Navigate(new Uri(NavigationContext.QueryString["StartURL"], UriKind.RelativeOrAbsolute)); 
      } 
      else if ((_deactivatedURL != null) && (e.NavigationMode != NavigationMode.Reset)) 
      { 
       // If there is a stored URL from our last 
       // session being deactivated, navigate there 
       if (Browser.Source != _deactivatedURL) 
       { 
        Browser.Navigate(_deactivatedURL); 
       } 
      } 
      else 
      { 
       // Not launched from a pinned tile... 
       // No stored URL from the last time the app was deactivated... 
       // So, just navigate to the home page 

       Browser.Navigate(new Uri(_homeURL, UriKind.RelativeOrAbsolute)); 
      } 
     } 

.... 

回答

1

我的問題是,該URL必須加載同步和異步不

不,你不能這樣做同步,但使用async/await你可以假裝它。

對於這一點,你可以使用的方法是這樣的(你甚至可以把它寫成擴展方法)

await Navigate(webBrowser1, "http://stackoverflow.com"); 
DoSomethingAfterNavigationCompleted(); 

Task Navigate(WebBrowser wb,string url) 
{ 
    var tcs = new TaskCompletionSource<object>(); 
    WebBrowserDocumentCompletedEventHandler documentCompleted = null; 
    documentCompleted = (o, s) => 
    { 
     wb.DocumentCompleted -= documentCompleted; 
     tcs.TrySetResult(null); 
    }; 

    wb.DocumentCompleted += documentCompleted; 
    wb.Navigate(url); 
    return tcs.Task; 
} 
+0

+1,雖然你並不需要'async'在'documentCompleted = async(o,s)'這個工作。用'try/finally'封裝'wb.Navigate'並在其中執行'await tcs.Task'也可能是一個好主意,以消除'DocumentCompleted'事件取消註冊失蹤時可能出現的情況。也許,像[this](http://stackoverflow.com/a/20934538/1768303)。 – Noseratio

+0

感謝您的回答。但知道我有問題,在Windows Phone 8.0 SDK中沒有lib System.Windows.Forms。我認爲System.Windows.Forms ist桌面應用程序... – RedLeffer