使用后台任务更新带有web服务数据的活动磁贴

问题描述:

我想知道是否有可能从后台任务中在我的应用程序中运行方法,而不仅仅是后台任务中的代码。我问的原因是我有一个后台任务,我想用webserive中的数据更新我的活动磁贴。我把后台任务里面的web服务电话如下:使用后台任务更新带有web服务数据的活动磁贴

public sealed class TileUpdater : IBackgroundTask 
{ 
    public async void Run(IBackgroundTaskInstance taskInstance) 
    { 
     ServiceReference.WebServiceSoapClient test = new ServiceReference.WebServiceSoapClient(); 
     var nb = await test.GetLatestDataAsync("temp"); 
     double temperature = nb.Value; 
     string unit = nb.Unit; 
     string latestTemp = " " + nb.Value + " " + nb.Unit; 


     var defferal = taskInstance.GetDeferral(); 

     var updater = TileUpdateManager.CreateTileUpdaterForApplication(); 
     updater.EnableNotificationQueue(true); 

     updater.Clear(); 

     for (int i = 1; i < 6; i++) 
     { 
      var tile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareText02); 
      tile.GetElementsByTagName("text")[0].InnerText = "Tile " + latestTemp; 
      tile.GetElementsByTagName("text")[1].InnerText = DateTime.Now.ToString("hh-mm"); 

      updater.Update(new TileNotification(tile)); 
     } 

     defferal.Complete(); 
    } 
} 

然而,当我运行应用程序时,什么也没有发生,我不明白的错误。它似乎停止了对web服务的调用。无论如何,我可以使后台任务调用在应用程序代码中的方法吗?

这里没有太多东西要去,所以我正在猜测。我的建议 - 移动GetDeferral线是第一:

public async void Run(IBackgroundTaskInstance taskInstance) 
{ 
    var defferal = taskInstance.GetDeferral(); 

    ServiceReference.WebServiceSoapClient test = new ServiceReference.WebServiceSoapClient(); 
    var nb = await test.GetLatestDataAsync("temp"); 
    double temperature = nb.Value; 
    string unit = nb.Unit; 
    string latestTemp = " " + nb.Value + " " + nb.Unit; 

    // move up 
    // var defferal = taskInstance.GetDeferral(); 
    ... 

您是否尝试过运行的后台任务的调试器,以确保没有错误发生?在Process组合框旁边的Debug Location工具栏中有一个下拉按钮,您可以使用它。只需启动您的应用程序,然后在下拉按钮中单击后台任务的名称即可。

enter image description here

Run方法将立即开始执行,你就可以调试它就像你的应用程序代码。我想你希望从任务中调用应用程序中现有方法的主要原因是能够正确调试它。

您可以在this article on MSDN中找到有关调试任务的更多详细信息。