2016-04-19 2 views
1

Windows Phone Silverlight 8.1アプリケーションのバックグラウンドタスクがあります。Windows Phoneを使用して非同期呼び出しを行うことができませんバックグラウンドタスク

バックグラウンドタスクはうまく動作しますが、非同期呼び出しメソッドを呼び出すと、この段階では単にフリーズします。デバッガを使用すると、デバッガは停止します。私はコードや何かを進めることはできません。

以下

が私のコードです:

public sealed class bgTask : IBackgroundTask 
    { 
     public async void Run(IBackgroundTaskInstance taskInstance) 
     { 
      BackgroundTaskDeferral _deferral = taskInstance.GetDeferral(); 

      DateTime timeNow = DateTime.Now; 
      TimeSpan minus28 = new TimeSpan(0, 28, 0); 
      DateTime timeGone = timeNow.Subtract(minus28); 

      int resultsCount = await GetCount(); 

      ToastTemplateType toastTemplate = ToastTemplateType.ToastText02; 
      XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate); 
      XmlNodeList textElements = toastXml.GetElementsByTagName("text"); 
      textElements[0].AppendChild(toastXml.CreateTextNode("New Pictures!")); 
      textElements[1].AppendChild(toastXml.CreateTextNode(resultsCount + " new images in your area")); 
      ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml)); 

      _deferral.Complete(); 
     } 

     private async Task<int> GetCount() 
     { 
      string page = "http://en.wikipedia.org/"; 

      // ... Use HttpClient. 
      using (HttpClient client = new HttpClient()) 
      using (HttpResponseMessage response = await client.GetAsync(page)) 
      using (HttpContent content = response.Content) 
      { 
       // ... Read the string. 
       string result = await content.ReadAsStringAsync(); 

       // ... Display the result. 
       if (result != null && 
       result.Length >= 50) 
       { 
        //resultsCount = 1888; 
       } 
      } 

      return 9999; 
} 

デバッグが、それはGetCountの()メソッドの内部で移動し、ただのawait GetCountの()部分に停止します。

これを数日間解決しようとしています。ヘルプは大いに感謝しています。 :)

+0

は、彼らが何の素敵な例を持っているhttps://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BackgroundTaskを参照してください。あなたがしようとしている。私があなたのカスタムセットアップ以外に見る唯一の違いは、クラスのスコープレベルでは常に 'BackgroundTaskDeferral'が定義され、Runでは定義されていないということです。私の答えがあなたの問題を解決した場合、 –

答えて

0

クラススコープで延期を定義する必要があります。これは、バックグラウンドタスクの作成と開始時に延期が要求されたためです。これについて

public sealed class bgTask : IBackgroundTask 
    { 
     BackgroundTaskDeferral _deferral = taskInstance.GetDeferral(); 
     public async void Run(IBackgroundTaskInstance taskInstance) 
     { 
      //Handle async stuff 
      _deferral.Complete(); 
     } 
    } 

詳しい情報はここで見つけることができます:https://msdn.microsoft.com/en-us/windows/uwp/launch-resume/create-and-register-a-background-task

+0

@ user3102785質問に回答してください。 –

関連する問題