2015-09-23 34 views
0

我想在我的C#W10 UWP應用中的鎖屏或壁紙設置圖像在BackgroundTask ...我可以在正常執行中做到這一點,但是當我將相同的代碼放入一個BackgroundTask,代碼掛起在StorageFile.CreateStreamedFileFromUriAsyncC#W10 UWP BackgroundTask StorageFile

// See if file exists already, if so, use it, else download it 
StorageFile file = null; 
try { 
    file = await ApplicationData.Current.LocalFolder.GetFileAsync(name); 
} catch (FileNotFoundException) { 
    if (file == null) { 
     Debug.WriteLine("Existing file not found... Downloading from web"); 

     file = await StorageFile.CreateStreamedFileFromUriAsync(name, uri, RandomAccessStreamReference.CreateFromUri(uri)); // hangs here!! 
     file = await file.CopyAsync(ApplicationData.Current.LocalFolder); 
    } 
} 

// Last fail-safe 
if (file == null) { 
    Debug.WriteLine("File was null -- error finding or downloading file..."); 
} else { 
    // Now set image as wallpaper 
    await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(file); 
} 

是否有BackgroundTasks說我不知道​​任何限制StorageFile?一些谷歌搜索沒有產生這樣的限制...

任何想法?

謝謝。

回答

1

「代碼掛起」是什麼意思?例外?開始操作但不會完成/返回? 我曾經(或有,我仍在努力)類似的問題,或者至少我認爲它是相似的。

也許這是一個異步配置上下文問題。

//not tested...but try ...AsTask().ConfigureAwait(false): 
file = await StorageFile.CreateStreamedFileFromUriAsync(name, uri, RandomAccessStreamReference.CreateFromUri(uri)).AsTask().ConfigureAwait(false); 

編輯: 啓動,但不會返回(斷點的代碼打不下一行),聽起來還是像的SynchronizationContext /死鎖問題...嗯...

你檢查(或確定)CreateStreamedFileFromUriAsync真的完成?

+0

「掛起」,它運行,但從來沒有返回..我設置了一個斷點後,它永遠不會到達那裏。沒有例外或任何東西。嗯 –

+0

與上面的更改相同的問題...感謝您的建議,雖然 –

+1

@Ubobo,仍然聽起來像一個SynchronizationContext/Deadlock問題。 Sry,目前不知道... – 1ppCH

0

發現它!

正如@ 1ppCH提到的,這聽起來像一個同步/死鎖問題......所以我試圖使任務同步:

file = Task.Run(async() => { 
    var _file = await StorageFile.CreateStreamedFileFromUriAsync(name, uri, RandomAccessStreamReference.CreateFromUri(uri)); 
    return await _file.CopyAsync(ApplicationData.Current.LocalFolder); 
}).Result; 

這似乎做的伎倆!

謝謝大家。