gpt4 book ai didi

c# - 如何从 Windows 8 中的 KnowFolders 检索文件?

转载 作者:太空宇宙 更新时间:2023-11-03 20:22:35 28 4
gpt4 key购买 nike

我想创建方法来获取 PictureFolder 中的文件列表。我创建了这个方法:

public Task<List<string>> GetImages()
{
var task = new Task<List<string>>(() =>
{
var files = new List<string>(5);
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
IReadOnlyList<IStorageItem> itemsList = picturesFolder.GetItemsAsync().GetResults();
foreach(var item in itemsList)
{
if(item is StorageFile)
{
files.Add(item.Name);
}
}
return files;

});
return task;
}

以及我测试此方法的代码:

 var pic = new PictureManager();
pic.GetImages().RunSynchronously();
List<string> images = pic.GetImages().Result;
bool hasValue = images.Count > 0;
Debug.WriteLine(string.Format("Has value {0}", hasValue));

我得到这个异常

System.InvalidOperationException was unhandled by user code
HResult=-2147483634
Message=A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)
Source=Windows.Foundation
StackTrace:
at Windows.Foundation.IAsyncOperation`1.GetResults()
at Praktyka.Models.PictureManager.<GetImages>b__0() in d:\Documents\Visual Studio 2012\Projects\Praktyka\Praktyka\Models\PictureManager.cs:line 63
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
InnerException:

在这一行(方法 GetImages)

 IReadOnlyList<IStorageItem> itemsList = picturesFolder.GetItemsAsync().GetResults();

如何解决这个问题?

最佳答案

RunSynchronously 方法在当前线程上启动一个任务。但是,从 GetItemsAsync 返回的任务已经启动,因此您会收到异常。

您需要重构代码以利用 async/await 关键字:

public async Task<List<string>> GetImages()
{
var files = new List<string>();
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
IReadOnlyList<IStorageItem> itemsList = await picturesFolder.GetItemsAsync();
foreach(var item in itemsList)
{
if(item is StorageFile)
{
files.Add(item.Name);
}
}
return files;
}

同样调用 GetImages 的方法应该利用等待:

var pic = new PictureManager();
List<string> images = await pic.GetImages();;
bool hasValue = images.Count > 0;
Debug.WriteLine(string.Format("Has value {0}", hasValue));

关于c# - 如何从 Windows 8 中的 KnowFolders 检索文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12606231/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com