【问题标题】:WebClient TimeOut Windows Phone 8WebClient 超时 Windows Phone 8
【发布时间】:2014-02-12 12:40:17
【问题描述】:

我想在等待 Web 请求期间运行任务。如果任务在请求可以返回响应之前完成,那么我会显示一条消息“服务器花费的时间太长”。我正在使用WebClient 对象,如何管理超时?

public Class Result
{
   protected override void OnNavigatedTo(NavigationEventArgs e)
   {
      if (NavigationContext.QueryString.TryGetValue("critere", out sCritere))
      {
         try
         {
            _datamanager = new DataManager();
            _datamanager.m_evt_Client_DownloadStringCompleted += OnDownloadStringCompleted;
            _datamanager.DownloadXmlData(DataManager.URL_RECHERCHE, sCritere);

            //HERE I NEED TO RUN A TIMER If the response is too long i would display a message                          

          }
          catch(Exception ex)
          {
             MessageBox.Show(ex.Message, "Erreur", MessageBoxButton.OK);
             NavigationService.GoBack();
             NavigationService.RemoveBackEntry();
          }
       }
    }
  }

public Class DataManager
{
   public void DownloadXmlData(string uri, string critere = "")
   {
      try
      {   
         WebClient client = new WebClient();
         client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
         client.Credentials = new NetworkCredential(UserSaved, PasswordSaved, domain);
         client.DownloadStringAsync(new Uri(uri + critere));
       }
       catch(WebException )
       {
          throw new WebException(MyExceptionsMessages.Webexception) ;
       }
       catch (Exception )
       {
          throw new UnknowException(MyExceptionsMessages.UnknownError);
       }
    }

   public void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
   {
      //raise Downloadstringcompleted event if error==null
   }
}

【问题讨论】:

    标签: windows-phone-8 timeout webclient


    【解决方案1】:

    你可以使用 BackgroundWorker..

    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += (s, e) =>
    {
        // your task to do while webclient is downloading
    };
    bw.RunWorkerCompleted += (s, e) =>
    {
        // check whether DownloadStringCompleted is fired or not
        // if not, cancel the WebClient's asynchronous call and show your message.
        client.CancelAsync();
        MessageBox.Show("message");
    }
    
    client.DownloadStringAsync(uri);
    bw.RunWorkerAsync();
    

    【讨论】:

    • 我发现了这个...也许我应该使用Task...看起来更简单更好...Task VS BGW
    猜你喜欢
    • 2013-10-05
    • 2014-02-28
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    相关资源
    最近更新 更多