Domanda

I want to update my live tile by creating and saving a writable bitmap image in scheduled task agent.my code works inside the app but in background task, it breaks into the debugger

I'm using this simple code:

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

        CreateWideTile();

        NotifyComplete();
    }

and my code to create and save image is this:

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);
            }
        }
    }

when I test the app, after executing background task, an error comes that point to Debugger.Break();

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

I don't understand the reason. my code works in foreground app but not in background ...

any solution ????

È stato utile?

Soluzione

You should use dispatcher, because WriteableBitmap.Render should be used in the UI thread:

protected override void OnInvoke(ScheduledTask task)
{    
  Deployment.Current.Dispatcher.BeginInvoke( () =>
  {
    CreateWideTile();
    NotifyComplete();
  } );
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top