C# W10 UWP BackgroundTask StorageFile

2019-09-11 09:26发布

问题:

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.