UWP/WinRT:如何在模型中的异步操作完成后执行UI任务

UWP/WinRT: How to perform a UI task upon completion of an asynchronous operation in a model?

本文关键字:异步操作 执行 任务 UI WinRT 模型 UWP      更新时间:2023-10-16

我遵循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,并提供了一个处理程序,该处理程序能够在事件被触发时执行任务。