后台任务正在跳过计划,有时每60分钟更新一次

时间:2011-12-17 13:52:24

标签: c# windows-phone-7 live-tile

我即将失去它...我有两个应用程序正在处理更新实时磁贴的工作后台任务。下载,解析实时图块的数据,然后动态创建图像并将其用作实时图块的背景。

一天或两天都工作正常,但随后更新开始表现得非常奇怪。我的应用程序的前两天两个活动磁贴都像发条一样每28分钟更新一次。但随后他们开始跳过更新。当应用B不更新实时磁贴时,应用A通常会更新,以便它们不会同时更新,而且每小时只更新一次。简单来说,它们已经过时了。

这真是令人沮丧,因为我需要能够依赖每30分钟更新一次的瓷砖(如果我有足够的电池,良好的接收等等)。

我真的很感激,如果有人可以帮助我,也许可以查看我的代码,看看是否有可能搞乱更新间隔(比如没有正确调用NotifyComplete)。我删除了一些代码,并试图简化它。请询问您是否还需要其他任何内容来理解这一点。

过去两个月我一直试图解决这个问题,尝试使用不同的手机并仔细检查代码。

您的帮助比您所知道的更受欢迎。 提前谢谢。

My OnInvoke function:

        Timer t = null;

        ShellToast toast = new ShellToast();


        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(strUrlHBH));
            request.Accept = "*/*";
            request.AllowAutoRedirect = true;

            // disable caching.
            request.Headers["Cache-Control"] = "no-cache";
            request.Headers["Pragma"] = "no-cache";

            t = new Timer(
                state =>
                {
                    if (string.Compare(state.ToString(), id, StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        //logger.Write("Timeout reached for connection [{0}], aborting download.", id);
                        runNotifyComplete = false;
                        NotifyComplete();
                        request.Abort();
                        t.Dispose();
                    }

                },
                id,
                timeout,
                0);

            request.BeginGetResponse(
                r =>
                {
                    try
                    {
                        if (t != null)
                        {
                            t.Dispose();
                        }

                        var httpRequest = (HttpWebRequest)r.AsyncState;
                        var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
                        using (var reader = new StreamReader(httpResponse.GetResponseStream()))
                        {

                            var response = reader.ReadToEnd();

                            Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
                            {
                                try
                                {

                                    //Parse the result

                                    if (boolResult) //If we have a result
                                    {


                                        Grid grid = new Grid();



                                        StackPanel sp = new StackPanel();
                                        sp.Height = 173;
                                        sp.Width = 173;



                                        //StreamResourceInfo info = Application.GetResourceStream(new Uri("Pin-to-start2.png", UriKind.Relative));


                                        if ((bool)settings["LiveTileMetro"] == true)
                                        {

                                            // create source bitmap for Image control (image is assumed to be alread 173x173)
                                            /*WriteableBitmap wbmp2 = new WriteableBitmap(1, 1);
                                            wbmp2.SetSource(info.Stream);
                                            Image img = new Image();
                                            img.Source = wbmp2;
                                            // add Image to Grid
                                            grid.Children.Add(img);
                                            strBackBackground = "Pin-to-start2.png";
                                        }
                                        else
                                        {*/
                                            sp.Background = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
                                            //sp.Background.Opacity = 0.0;
                                            strBackBackground = "";
                                        }

                                        StreamResourceInfo info;

                                        //GC.Collect();
                                        info = Application.GetResourceStream(new Uri("/MyApp;component/images/Icons/livetile/livetile.png", UriKind.Relative));


                                        WriteableBitmap wbmp3 = new WriteableBitmap(1, 1);
                                        try
                                        {
                                            wbmp3.SetSource(info.Stream);
                                        }
                                        catch
                                        {
                                        }
                                        Image img3 = new Image();
                                        img3.Source = wbmp3;
                                        // add Image to Grid
                                        img3.Width = 173;
                                        img3.Height = 173;
                                        img3.Margin = new Thickness { Left = 0, Bottom = 0, Right = 0, Top = 0 };


                                        TextBlock txtTemperature = new TextBlock();
                                        TextBlock txtTemperatureRing = new TextBlock();

                                        txtTemperature.Foreground = new SolidColorBrush(Colors.White);
                                        txtTemperature.Text = strTemp;
                                        txtTemperature.TextAlignment = TextAlignment.Right;
                                        txtTemperatureRing.Style = (Style)Application.Current.Resources["PhoneTextTitle3Style"];
                                        txtTemperatureRing.FontFamily = new FontFamily("Segoe WP Light");
                                        txtTemperatureRing.FontSize = 40;
                                        txtTemperatureRing.Foreground = new SolidColorBrush(Colors.White);
                                        txtTemperatureRing.Text = "°";
                                        txtTemperatureRing.TextAlignment = TextAlignment.Right;

                                            txtTemperature.FontFamily = new FontFamily("Segoe WP Light");
                                            txtTemperature.FontSize = 60;
                                            txtTemperature.Margin = new Thickness { Left = 0, Bottom = 0, Right = 0, Top = -75 };
                                            txtTemperature.Height = 80;
                                            txtTemperature.Width = 145;
                                            txtTemperatureRing.Margin = new Thickness { Left = 128, Bottom = 0, Right = 0, Top = -97 };
                                            txtTemperatureRing.Height = 50;
                                            txtTemperatureRing.Width = 39;

                                        sp.Children.Add(img3);
                                        sp.Children.Add(txtTemperature);
                                        sp.Children.Add(txtTemperatureRing);


                                        //call measure, arrange and updatelayout to prepare for rendering
                                        sp.Measure(new Size(173, 173));
                                        sp.Arrange(new Rect(0, 0, 173, 173));
                                        sp.UpdateLayout();
                                        grid.Children.Add(sp);


                                        WriteableBitmap wbmp = new WriteableBitmap(173, 173);
                                        wbmp.Render(grid, null);
                                        wbmp.Invalidate();


                                        //write image to isolated storage
                                        string sIsoStorePath = @"\Shared\ShellContent\tile.png";
                                        using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
                                        {
                                            //ensure directory exists
                                            String sDirectory = System.IO.Path.GetDirectoryName(sIsoStorePath);
                                            if (!appStorage.DirectoryExists(sDirectory))
                                            {
                                                appStorage.CreateDirectory(sDirectory);
                                            }

                                            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(sIsoStorePath, System.IO.FileMode.Create, appStorage))
                                            {
                                                wbmp.SaveJpeg(stream, 173, 173, 0, 100);
                                            }
                                        }


                                        /// If application uses both PeriodicTask and ResourceIntensiveTask


                                            //ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("TileID=2"));
                                            ShellTile TileToFind = ShellTile.ActiveTiles.First();

                                            //test if Tile was created
                                            if (TileToFind != null)
                                            {
                                                StandardTileData NewTileData = new StandardTileData
                                                {
                                                    BackgroundImage = new Uri("isostore:Shared/ShellContent/tile.png", UriKind.Absolute),
                                                    Title = strTitle,
                                                    Count = null,
                                                    BackTitle = (string)settings["SelectedCityName"],
                                                    BackBackgroundImage = new Uri(strBackBackground, UriKind.Relative),
                                                    BackContent = strWind + Environment.NewLine + strPrecipitation
                                                };

                                                //ShellTile.Create(new Uri("/MainPage.xaml?TileID=2", UriKind.Relative), NewTileData);
                                                TileToFind.Update(NewTileData);

                                            }
                                        }



                                        if (runNotifyComplete == true)
                                        {
                                            runNotifyComplete = false;
                                            NotifyComplete();
                                        }
                                    }//If matches.count
                                }
                                catch
                                {
                                    if (runNotifyComplete == true)
                                    {
                                        runNotifyComplete = false;
                                        NotifyComplete();
                                    }
                                }
                                finally
                                {
                                    if (runNotifyComplete == true)
                                    {
                                        runNotifyComplete = false;
                                        NotifyComplete();
                                    }
                                }
                            }));
                        }



                        if (runNotifyComplete == true)
                        {
                            runNotifyComplete = false;
                            NotifyComplete();
                        }

                    }
                    catch
                    {


                        // error handling.
                        if (runNotifyComplete == true)
                        {

                            runNotifyComplete = false;
                            NotifyComplete();
                        }
                    }
                    finally
                    {
                    }
                },
                request);
        }
        catch
        {
            if (runNotifyComplete == true)
            {
                runNotifyComplete = false;
                NotifyComplete();
            }
        }
        finally
        {
        }

编辑1:这是初始化后台任务的代码     MessageBox.Show(MyResources.LiveTileToggleMsgBoxText,“Live tile”,MessageBoxButton.OK);

              //start background agent 
            PeriodicTask periodicTask = new PeriodicTask("AppPeriodicAgent0440");

            periodicTask.Description = "Periodic task for APP that updates the LiveTile .";
            periodicTask.ExpirationTime = System.DateTime.Now.AddDays(14);

            // If the agent is already registered with the system,
            if (ScheduledActionService.Find(periodicTask.Name) != null)
            {
                ScheduledActionService.Remove("AppPeriodicAgent0440");
            }

            try
            {
                //only can be called when application is running in foreground
                ScheduledActionService.Add(periodicTask);
            }
            catch
            {
            }

编辑2: 每次退出应用程序时都会运行此代码,以使后台任务保持活动状态。我把它放在OnNavigatedFrom中以避免减慢应用程序的启动速度

//start background agent 
                        PeriodicTask periodicTask = new PeriodicTask("AppPeriodicAgent0440");

                        periodicTask.Description = "Periodic task for APP that updates the LiveTile.";
                        periodicTask.ExpirationTime = System.DateTime.Now.AddDays(14);

                        // If the agent is already registered with the system,
                        if (ScheduledActionService.Find(periodicTask.Name) != null)
                        {
                            ScheduledActionService.Remove("AppPeriodicAgent0440");
                        }

                        //only can be called when application is running in foreground
                        ScheduledActionService.Add(periodicTask);

2 个答案:

答案 0 :(得分:1)

如果您阅读后台代理概述 http://msdn.microsoft.com/en-us/library/hh202942(v=vs.92).aspx您会看到它会详细说明您不会遵循计划的几种情况。例如:

  

省电模式是用户可以在设备上启用的选项   表明电池寿命应优先考虑。如果是这种模式   启用后,即使间隔已过,也可能无法运行定期代理

答案 1 :(得分:0)

无法保证计划任务将按预期计划运行。它甚至在执行时间表中有+/- 10分钟的条款。

根据您的问题,没有关于您在预计计划运行时如何记录设备上可能发生的其他事件/任务的信息。

由于您没有记录错误,超时或检查任务的LastExitReason,因此您可能会遇到各种原因。

如果我不得不猜测问题所在,根据您提供的信息,我认为问题出在Web请求(网络或服务器)上,请求中的错误会导致UI没有更新。

无法保证磁贴将按预测的时间表更新。如果您必须根据您的情况/要求完全更新,那么此平台将无法提供该保证。

如果您需要保持多个图块同步,我可以通过同一过程更新所有图块来实现此目的。
这样,即使从时间角度更新磁贴时出现不一致,它们也会彼此同步。