0

我想通过在计划任务代理中创建和保存可写位图图像来更新我的实时磁贴。我的代码在应用程序内部工作,但在后台任务中,它会进入调试器

我正在使用这个简单的代码:

    protected override void OnInvoke(ScheduledTask task)
    {
#if DEBUG_AGENT
        ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
#endif

        CreateWideTile();

        NotifyComplete();
    }

我创建和保存图像的代码是这样的:

private void CreateWideTile()
    {
        int width = 691;
        int height = 336;
        string imagename = "WideBackground";

        WriteableBitmap b = new WriteableBitmap(width, height);

        var canvas = new Grid();
        canvas.Width = b.PixelWidth;
        canvas.Height = b.PixelHeight;

        var background = new Canvas();
        background.Height = b.PixelHeight;
        background.Width = b.PixelWidth;

        //Created background color as Accent color    
        SolidColorBrush backColor = new SolidColorBrush(Colors.Red);
        background.Background = backColor;

        var textBlock = new TextBlock();
        textBlock.Text = "Example text";
        textBlock.FontWeight = FontWeights.Normal;
        textBlock.TextAlignment = TextAlignment.Left;
        textBlock.Margin = new Thickness(20, 20, 0, 0);
        textBlock.TextWrapping = TextWrapping.Wrap;
        textBlock.Foreground = new SolidColorBrush(Colors.White); //color of the text on the Tile    
        textBlock.FontSize = 30;

        canvas.Children.Add(textBlock);

        b.Render(background, null);
        b.Render(canvas, null);
        b.Invalidate(); //Draw bitmap

        //Save bitmap as jpeg file in Isolated Storage    
        using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream imageStream = new IsolatedStorageFileStream("/Shared/ShellContent/" + imagename + ".jpg", System.IO.FileMode.Create, isf))
            {
                b.SaveJpeg(imageStream, b.PixelWidth, b.PixelHeight, 0, 100);
            }
        }
    }

当我测试应用程序时,在执行后台任务后,出现指向 Debugger.Break() 的错误;

private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    {
        if (Debugger.IsAttached)
        {
            // An unhandled exception has occurred; break into the debugger
            Debugger.Break();
        }
    }

我不明白原因。我的代码在前台应用程序中工作,但不在后台......

有什么解决办法???

4

1 回答 1

1

您应该使用调度程序,因为应该在 UI 线程中使用 WriteableBitmap.Render:

protected override void OnInvoke(ScheduledTask task)
{    
  Deployment.Current.Dispatcher.BeginInvoke( () =>
  {
    CreateWideTile();
    NotifyComplete();
  } );
}
于 2014-02-23T22:23:20.733 回答