使用 UWP 中的 IAsyncOperation 继续执行任务

Task continuation with IAsyncOperation in UWP

本文关键字:继续 执行任务 IAsyncOperation 中的 UWP 使用      更新时间:2023-10-16

我有一个 c++ 类对象,它在 uwp 应用程序的后台执行一些处理。

它的进程操作由 Unity 的"更新"方法 ~60fps 通过 UWP IAsyncOperation 调用。

该类有一个 isBusy 属性,该属性设置为在调用操作后true,以便在操作完成之前阻止从 Unity 再次调用它。

使用任务延续,我想在处理完成并通过IAsyncOperation返回后将其设置为 false。


IAsyncOperation<ResultsWrapper^>^ SomeClass::SomeClassUpdateMethod() {
    return concurrency::create_async([this]() -> ResultsWrapper^
    { 
        // Block processing
        SomeClass::isBusy = true;
        // Process image and return to await
        LongRunningTask().then([this]() {
            return SomeClass::TaskResults; 
        }).then([this]() {
            isBusy = false;
        });
    });
}
concurrency::task<void> SomeClass::LongRunningTask(){
    auto results = ref new TaskResults();
    '''Work happens here'''
    SomeClass::TaskResults = results;
}

我希望发生的事情是将ResultWrapper对象返回到调用应用程序(Unity(的主线程,然后将对象的isBusy标志设置为任务继续为false。

发生的情况是:

Error C2338 incorrect parameter type for the callable object in 'then'; consider _ExpectedParameterType or task<_ExpectedParameterType> (see below) ....includeppltasks.h

发生此异常的原因是您没有在任务链中返回 ResultsWrapper^ 类型。您编写的第二个返回意味着将值传递给下一个链以供使用,而不是返回任务的值。因此,您应该像以下代码一样编写以正确返回值。

IAsyncOperation<ResultsWrapper^>^ SomeClass::SomeClassUpdateMethod() 
{
    return concurrency::create_async([this]() -> concurrency::task<ResultsWrapper^>
    { 
        SomeClass::isBusy = true;
        return LongRunningTask().then([this]() -> ResultsWrapper^
        {
            isBusy = false;
            return SomeClass::TaskResults; 
        });
    });
}

代码 "return LongRunningTask((.then(this ->ResultsWrapper^(" 表示将 ResultsWrapper^ 对象转换为任务并返回任务。

"LongRunningTask">方法的返回值是task<void>,所以仍然需要返回一个task<void>值。

concurrency::task<void> SomeClass::LongRunningTask()
{
    return concurrency::create_task(
    [this]()
    {
        auto results = ref new TaskResults();
        '''Work happens here'''
        SomeClass::TaskResults = results;
    });
}