【问题标题】:Windows 8 - How to get nested folder properly?Windows 8 - 如何正确获取嵌套文件夹?
【发布时间】:2013-04-12 19:20:38
【问题描述】:

我有一个绑定到从磁盘加载图像的对象集合的 GridView。

对象在可见时被放入堆栈,图像按顺序从堆栈中加载。

问题是 GetFolderAsync() 在包含对象的 ScrollViewer 停止滚动之前不会返回。

代码如下:

    public static async Task<StorageFolder> GetFileFolderAsync(String fileUrl)
    {
        try
        {
            string filePathRelative = DownloadedFilePaths.GetRelativeFilePathFromUrl(fileUrl);
            string[] words = filePathRelative.Split('\\');
            StorageFolder currentFolder = await DownloadedFilePaths.GetAppDownloadsFolder();
            for (int i = 0; (i < words.Length - 1); i++)
            {
                //this is where it "waits" for the scroll viewer to slow down/stop
                currentFolder = await currentFolder.GetFolderAsync(words[i]);
            }
            return currentFolder;
        }
        catch (Exception)
        {
            return null;
        }
    }

我已将其精确定位到获取包含图像的文件夹的那一行。这甚至是获取嵌套文件夹的正确方法吗?

【问题讨论】:

    标签: c# windows asynchronous windows-8 windows-runtime


    【解决方案1】:

    您可以尝试使用ConfigureAwait(false) 在线程池线程上运行for 循环:

    public static async Task<StorageFolder> GetFileFolderAsync(String fileUrl)
    {
        try
        {
            string filePathRelative = DownloadedFilePaths.GetRelativeFilePathFromUrl(fileUrl);
            string[] words = filePathRelative.Split('\\');
            // HERE added ConfigureAwait call
            StorageFolder currentFolder = await
                DownloadedFilePaths.GetAppDownloadsFolder().ConfigureAwait(false);
            // Code that follows ConfigureAwait(false) call will (usually) be 
            // scheduled on a background (non-UI) thread.
            for (int i = 0; (i < words.Length - 1); i++)
            {
                // should no longer be on the UI thread, 
                // so scrollviewer will no longer block
                currentFolder = await currentFolder.GetFolderAsync(words[i]);
            }
            return currentFolder;
        }
        catch (Exception)
        {
            return null;
        }
    }
    

    请注意,在上述情况下,由于没有在 UI 上完成任何工作,您可以使用ConfigureAwait(false)。例如,由于在ConfigureAwait 之后有一个与 UI 相关的调用,因此以下内容将不起作用:

    // HERE added ConfigureAwait call
    StorageFolder currentFolder = await
        DownloadedFilePaths.GetAppDownloadsFolder().ConfigureAwait(false);
    // Can fail because execution is possibly not on UI thread anymore:
    myTextBox.Text = currentFolder.Path;
    

    【讨论】:

      【解决方案2】:

      原来我用来确定对象可见性的方法阻塞了 UI 线程。

      我有一个绑定到从磁盘加载图像的对象集合的 GridView。

      对象在可见时被放入堆栈,图像按顺序从堆栈中加载出来。

      问题是 GetFolderAsync() 在包含对象的 ScrollViewer 停止滚动之前不会返回。

      【讨论】:

        猜你喜欢
        • 2021-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-26
        • 2016-03-09
        • 2011-11-12
        相关资源
        最近更新 更多