【问题标题】:C# W10 UWP BackgroundTask StorageFileC# W10 UWP BackgroundTask StorageFile
【发布时间】:2015-09-23 05:24:05
【问题描述】:

我正在尝试在 BackgroundTask 中的 C# W10 UWP 应用程序中将图像设置为锁屏或墙纸...在正常执行中我可以做到这一点,但是当我将相同的代码放入 @987654322 @,代码挂在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);
}

BackgroundTasks 中的StorageFile 是否有任何我不知道的限制?一些谷歌搜索没有产生这样的限制......

有什么想法吗?

谢谢。

【问题讨论】:

    标签: c# stream backgroundworker background-task storagefile


    【解决方案1】:

    “代码挂起”是什么意思?例外?开始操作但不会完成/返回? 我有(或有,我仍在处理)类似的问题,或者至少我认为它是类似的。

    可能是异步配置上下文问题。

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

    编辑: 启动,但不会返回(下一行代码的断点未命中),听起来仍然像 SynchronizationContext/Deadlock 问题...嗯...

    您是否检查(或确定)CreateStreamedFileFromUriAsync 真的完成了吗?

    【讨论】:

    • “挂起”,它运行但永远不会返回。我在之后的行上设置了一个断点,它永远不会到达那里。没有例外或任何东西。嗯
    • 与上述更改相同的问题...感谢您的建议
    • @Ubobo,听起来仍然像 SynchronizationContext/Deadlock 问题。不好意思,暂时不知道……
    • 谢谢@1ppCH,我已经找到并添加了一个解决方案到这个线程:)
    【解决方案2】:

    找到了!

    正如@1ppCH 提到的,这听起来像是一个同步/死锁问题......所以我尝试让任务同步:

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

    这似乎成功了!

    谢谢大家。

    【讨论】:

      猜你喜欢
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 2017-01-26
      • 2017-02-06
      • 1970-01-01
      • 2016-10-18
      相关资源
      最近更新 更多