在Windows 8 metro应用程序上同步两个ppl任务

Synchronizing two ppl task on Windows 8 metro app

本文关键字:两个 任务 ppl 同步 Windows metro 应用 程序上 应用程序      更新时间:2023-10-16

这是msdn的地铁摄像头应用程序。此代码用于显示相机的预览。相机列表将显示在组合框中。用户可以选择相机来查看所选相机的预览,但当我更改相机时,它首先释放资源,然后启动所选相机预览。由于释放过程是异步过程,它在后台运行,所以在释放之前,它启动所选相机的预览,同时删除"m_MediaCaptureMgr"指针,程序崩溃。

在Win 32中,我可以使用waitforSingle对象来同步它。我想知道如何在WinRT和ppl任务中最好地同步。

void CameraApp::MainPage::cmbCameraSelector_SelectionChanged(Platform::Object^ sender,  Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
{
if(m_DeviceVector.size() > 0)
{
    m_CaptureInitSettings->VideoDeviceId = m_DeviceVector[cmbCameraSelector->SelectedIndex]->Id;
    InitMediaCapture();
}
}
void CameraApp::MainPage::InitMediaCapture()
{
ReleaseMediaCapture();
//Sleep(3000);
auto _this = this;
m_MediaCaptureMgr = ref new MediaCapture();
task<void> stratPreview(m_MediaCaptureMgr->InitializeAsync(m_CaptureInitSettings));
stratPreview.then([_this]
{
    _this->previewElement->Source = _this->m_MediaCaptureMgr;
    task<void> startPrev(_this->m_MediaCaptureMgr->StartPreviewAsync());
    startPrev.then([=]
    {
        return _this->GetCameraSettings();
    });     
});
}    
void CameraApp::MainPage::ReleaseMediaCapture()
{
if (m_MediaCaptureMgr )
{
    auto prevOp = m_MediaCaptureMgr->StopPreviewAsync();
    task<void> releaseMediaCapture(m_MediaCaptureMgr->StopPreviewAsync());
    releaseMediaCapture.then([=]
    {
        m_MediaCaptureMgr = nullptr;
        bRelease = false;
    });
}
}

在WinRT中,您可以使用并发::事件类。方法事件::wait应该是WaitforSingleObject 的一个很好的替代品