今天要給大家分享的是關於BackgroundTask。在此之前,我們先看看這個問題:VS2011 無法捕獲的Crash(崩潰)。
在我們某個版本發布了Alpha之后,測試人員就反饋說我們的應用不像前一個版本那么穩定了,總是會自動關閉,或者重新啟動,而且操作步驟沒有規律,浮現概率低。
我的第一反應是:系統的問題。因為在自測的過程中也有碰到類似問題,比如:在Debug某個功能的時候(通常需要運行大概5分鍾或者更長時間),應用程序就會自動關閉,並且vs自動解除Debug狀態。這讓我很納悶,如果有異常,應該在Debug狀態下拋出給開發者,怎么會無故關閉Debug狀態呢??
直到我們臨近官方提交應用的截止日期,這個問題被無限放大,成為我們當時最難以解決又不得不解決的問題。沒有log、沒有異常拋出,我們當時只能嘗試着每一條通往答案的路。
后來我們發現,當我們只是啟動了程序,什么都不做的情況下,依然會Crash,Crash的時間都不定,大概在5-15分鍾。我回想了下,當時只有全局的Timer在運行,但是當我們把Timer去掉后,Crash的情況依然存在。
於是我們想到了Background,難道程序在運行的時候,Background也在執行??官方文檔中描述了
If a background task executes within the app process, the background task infrastructure might need to change the state of the app:
· Running: If the app is running, it is already in the foreground and the background task is simply launched within the app.
· Suspended: If the app is suspended, most of its threads are unfrozen and the background task is launched. For details, see “Threading model for background tasks hosted in the app,” later in this paper.
· Terminated: If the app is terminated, it is not running at the time of the trigger so the app is launched and the background task is run. The app activation does not involve UI, and it does not bring the app to the foreground.
也就是說,在程序運行的時候,BackgroundTask也在運行。但是我們的代碼是根據官方提供的Sample中的代碼寫的,設置也一樣,應該不會錯啊。經過我們的測試,官方提供的Sample也會出現Crash的情況。。。原因是,我們的開發環境曾經升級了一個內部版本,代碼有些變動,但是官方文檔中並沒有提及相關的變動和相關的方法,這在一定程度上影響了我們的正常開發進度。(但是在此還是要感謝一下微軟中國對我們的支持,幫我們向總部反應情況)
如下圖,由於我們的BackgroundTask是時間觸發的,每15分鍾觸發一次,因此我們在配置文件的Declarations選項卡中添加BackgroundTasks,然后再右側的設置中只勾選Timer,切Executable項的內容需要為空(官方Sample中勾選了多個,並且Executable項中的內容為:backgroundTaskHost.exe)
然后再試試,Crash現象沒有了,BackgroundTask也能正常運行了。我們的努力沒有白費啊。希望能夠幫助到碰到相關問題的開發者們。