0

我想通過創建和計劃任務agent.my代碼保存寫位圖圖像來更新我的動態磁貼的作品裏面的應用程序,但在後臺任務,它中斷到調試如何在Windows Phone 8的ScheduledTask中使用Writablebitmap?

我使用這個簡單的代碼:

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

我不明白原因。我的代碼在前臺應用程序,但不是在後臺...

任何解決????

+1

,什麼是拋是獲取異常?也許內存不足? –

+0

沒有它不涉及存儲 – FSystem

回答

1

你應該使用調度,因爲WriteableBitmap.Render應該在UI線程中使用:

protected override void OnInvoke(ScheduledTask task) 
{  
    Deployment.Current.Dispatcher.BeginInvoke(() => 
    { 
    CreateWideTile(); 
    NotifyComplete(); 
    }); 
} 
+0

oh.what一個簡單的解決方案!我的問題解決了,謝謝 – FSystem

相關問題