我正在编写一个小型 WinRT 程序来异步创建一个文件夹和一个文件。简化后的代码如下:
auto createFolderOp = ApplicationData::Current->LocalFolder->CreateFolderAsync(L"DummyFolder", CreationCollisionOption::OpenIfExists);
create_task(createFolderOp).then([](task<StorageFolder ^> folder)
{
StorageFolder ^tempFolder;
tempFolder = uploadFolder.get();
return tempFolder->CreateFileAsync(L"DummyFile.txt", CreationCollisionOption::ReplaceExisting);
}).then([] (task<StorageFile ^> dummyFile)
{
StorageFile ^file;
file = dummyFile.get();
FileIO::WriteTextAsync(file, L"Dummy Content");
});
在这段代码的执行过程中,我想在每一步更新我的用户界面。例如,我有一个文本 block ,在每个步骤中我都想更新它以显示不同的文本,例如:
Create Folder Succeed...
Create File Succeed...
Write File Succeed...
等
如何从异步任务访问 UI 元素?这样做的最佳做法是什么?
最佳答案
您需要从 UI 线程更新 UI。我前一段时间写了一篇关于从不同类型的 Windows Phone 应用程序获取 UI 线程的帖子,它应该也适用于 Windows RT 应用程序:http://robwirving.com/2013/07/17/guide-to-getting-to-the-ui-thread-for-any-type-of-windows-phone-8-app/
如果您使用的是 Windows Xaml,您应该能够从 CoreWindow 对象获取 Dispatcher 并使用调度程序的 RunAsync 运行 lambda。方法。
如果您尝试从 WinRT 组件访问 UI 线程,那会有点困难,但我这里有一个方法:http://robwirving.com/2014/06/02/getting-to-the-ui-thread-from-a-windows-phone-winrt-component/
关于c++ - 从 WinRT 中的异步任务 lambda 更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24787969/