C# W10 UWP BackgroundTask StorageFile

左心房为你撑大大i 提交于 2019-12-25 14:05:08

问题


I'm trying to set an image to lockscreen or wallpaper in my C# W10 UWP app in a BackgroundTask... I can do this just fine in normal execution, but when I put the same code into a BackgroundTask, the code hangs at StorageFile.CreateStreamedFileFromUriAsync.

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

Are there any restrictions to StorageFile in BackgroundTasks that I'm unaware of? Some googling yielded no such restrictions...

Any ideas?

Thanks.


回答1:


What does "the code hangs" mean? Exception? Starts the operation but wont finish/return? I had (or have, I'm still working on) a similar problem, or at least I think it's similar.

Maybe it's a async-configure-context problem.

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

Edit: Starts, but wont return (breakpoint on next line of code not hit), sounds still like a SynchronizationContext/Deadlock problem... hmm...

Have you checked (or make sure) that CreateStreamedFileFromUriAsync really finishes?




回答2:


Found it!

As @1ppCH mentioned, it sounded like a sync/deadlock issue... So I tried making the task synchronous:

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

Which seemed to do the trick!

Thanks all.



来源:https://stackoverflow.com/questions/32731566/c-sharp-w10-uwp-backgroundtask-storagefile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!