UWP/WinRT:如何在模型中的异步操作完成后执行UI任务
UWP/WinRT: How to perform a UI task upon completion of an asynchronous operation in a model?
我遵循MVVM模式,并有一个称为DocumentStore
的模型。该类有如下方法:
void DocumentStore::Open_Document(StorageFile^ file) {
create_task(FileIO::ReadTextAsync(file))
.then([this, file](String^ fileContents)
{
// Take the fileContents and add them to internal data structure
});
}
我的ViewModel正在弹出一个FileOpenPicker
来获得一个文件,然后它作为参数馈送到Open_Document
:
create_task(picker->PickSingleFileAsync())
.then([this](StorageFile^ file)
{
m_DocStore->Open_Document(file);
// Target location to do something
}
);
我希望能够在Open_Document
内部的任务完成后执行操作,即在fileContents被处理后。
是否有一种方法可以让我的模型通知任何感兴趣的侦听器任务已经完成?
或者我的模型的Open_Document
方法实际上本身是异步的吗?但是,我需要在任务内部处理数据结构,这不会导致我的方法在不同的线程上下文中运行吗?我在c++/CX工作,但会采取任何帮助,我可以得到。
如果我理解正确,流程如下:
打开文件->读取内容->处理内容->做STH else
可以将异步操作推送到任务链上,并使用create_async方法创建一个新的异步操作。
下面是代码供您参考:
create_task(StorageFile::GetFileFromApplicationUriAsync(ref new Windows::Foundation::Uri("ms-appx:///Assets/XMLFile.xml")))
.then([](StorageFile^ file) {
WriteLine("Read the file");
return FileIO::ReadTextAsync(file);
}).then([](task<String^> task) {
String ^ text = task.get();
WriteLine("Content: " + text);
return create_async([text]() {
WriteLine("Process the text: " + text);
});
}).then([](task<void> task) {
task.get();
WriteLine("Do STH else");
});
我张贴了我最终的答案,但我接受了Jeffrey Chen的答案,因为它帮助我到达了那里。
我的模型现在有一个事件DocOpened
。这是在Open_Document
完成时触发的。我为这个事件订阅了我的ViewModel,并提供了一个处理程序,该处理程序能够在事件被触发时执行任务。
相关文章:
- 无法在 WinRT 中获取异步操作结果 (Windows::Foundation::IAsyncOperating 接口
- 异步操作的 Asio 处理程序在其同步对应项正常工作时不会调用
- 我不明白异步操作如何使HTTP服务器并发
- 每个操作执行两次
- 提升::Asio 使用异步操作时传输的字节
- 有没有办法为任何函数编写通用代码,以便它可以(异步)执行并从线程池中获得返回值?
- 如何编写异步操作?
- 发生哪些线程异步操作
- C 11异步操作在树上的操作
- 在 boost::asio 中启动异步操作和运行io_service的正确顺序
- 如何实现多线程异步操作
- FTP异步操作[Wininet C++]上的ERROR_IO_PENDING
- 使用带有boost::asio异步操作的自定义streambuf
- 提升 ASIO,如何取消异步操作
- 提升异步操作不起作用(对我来说)
- 在同一条链中执行异步操作
- 将异步操作的处理程序绑定到另一个类的非静态成员
- 如果一个basic_waitable_timer在仍有异步操作等待的情况下被销毁,该怎么办
- 如何用c++ boost::asio顺序执行异步操作
- UWP/WinRT:如何在模型中的异步操作完成后执行UI任务