加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

windows-runtime – 如何等待IAsyncAction?

发布时间:2020-12-13 22:41:43 所属栏目:Windows 来源:网络整理
导读:在 Windows应用商店应用中,C(C#虽然类似),做类似的事情 IAsyncAction^ Action = CurrentAppSimulator::ReloadSimulatorAsync(proxyFile);create_task( Action ).then([this](){}.wait(); 导致未处理的异常.通常是 Microsoft C++ exception: Concurrency::inv
在 Windows应用商店应用中,C(C#虽然类似),做类似的事情
IAsyncAction^ Action = CurrentAppSimulator::ReloadSimulatorAsync(proxyFile);
create_task( Action ).then([this]()
{
}.wait();

导致未处理的异常.通常是

Microsoft C++ exception: Concurrency::invalid_operation at memory location 0x0531eb58

在尝试使用它之前,我需要完成该操作以获取我的In App Purchase信息.
这里奇怪的是除了IAsyncAction以外的任何其他东西都等待. IAsyncOperation和IAsyncOperationWithProgress工作正常,但是这个?异常然后崩溃.

说实话,我不知道IAsyncOperation和IAsyncAction之间有什么区别,它们看起来和我类似.

更新:

通过分析此页面http://msdn.microsoft.com/en-us/library/vstudio/hh750082.aspx,您可以发现IAsyncAction只是一个没有返回类型的IAsyncOperation.但是,您可以看到大多数IAsyncAction-s都是可以等待的.但真正的问题是某些Windows函数只是想在特定线程上执行(出于某种原因). ReloadSimulatorAsync就是一个很好的例子.

使用这样的代码:

void WaitForAsync( IAsyncAction ^A )
{   
    while(A->Status == AsyncStatus::Started)
    {
        std::chrono::milliseconds milis( 1 );
        std::this_thread::sleep_for( milis );
    }   
    AsyncStatus S = A->Status;  
}

导致无限循环.如果调用其他功能,它实际上是有效的.这里的问题是,如果一切都是异步,为什么需要在特定线程上执行任务?它应该是RunOn(Main / UI)Thread或类似的而不是Async.

求助,见答案;

在完成创建它之后调用concurrency :: task会使得首先完成任务失败.

您必须意识到,在Windows运行时,有许多异步操作无法(或不应该)在UI线程上运行(或等待);你找到了其中之一,现在你正试图等待它.您可能会遇到异常,而不是可能导致死锁.

要解决这个问题,你需要使用a continuation.你大部分都在那里;你已经定义了一个延续函数:

IAsyncAction^ Action = CurrentAppSimulator::ReloadSimulatorAsync(proxyFile);
create_task( Action ).then([this]()
{
}).wait();

// do important things once the simulator has reloaded
important_things();

……但你没有使用它.您传递的函数的目的是在任务完成后从UI线程调用.所以,相反,你应该这样做:

IAsyncAction^ Action = CurrentAppSimulator::ReloadSimulatorAsync(proxyFile);
create_task( Action ).then([this]()
{
    // do important things once the simulator has reloaded
    important_things();
});

您的重要重载后代码将在任务完成后才会运行,并且它将在后台线程上运行,因此它不会阻止或死锁UI.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读