【问题标题】:BitmapImage SetSourceAsync in WinRT c++WinRT c ++中的BitmapImage SetSourceAsync
【发布时间】:2014-11-13 22:40:34
【问题描述】:

我是 WinRT c++ 的新手。我正在尝试从 C# 传递 StorageFile 图像并打开文件并将其设置为 WinRT 中 BitmapImage 中的源以提取图像的高度和宽度。我正在使用以下代码。

auto openOperation = StorageImageFile->OpenAsync(FileAccessMode::Read); // from http://msdn.microsoft.com/en-us/library/windows/desktop/hh780393%28v=vs.85%29.aspx
openOperation->Completed = ref new
    AsyncOperationCompletedHandler<IRandomAccessStream^>(
    [=](IAsyncOperation<IRandomAccessStream^> ^operation, AsyncStatus status)
{
    auto Imagestream = operation->GetResults(); 
    BitmapImage^ bmp = ref new BitmapImage();
    auto bmpOp = bmp->SetSourceAsync(Imagestream);
    bmpOp->Completed = ref new 
        AsyncActionCompletedHandler (
        [=](IAsyncAction^ action, AsyncStatus status)
    {
        action->GetResults();
        UINT32 imageWidth = (UINT32)bmp->PixelWidth;
        UINT32 imageHeight = (UINT32)bmp->PixelHeight;
    });
});

此代码似乎不起作用。在 BitmapImage^ bmp = ref new BitmapImage(); 之后调试器停止说没有找到源代码。 你能帮我写出正确的代码吗?

【问题讨论】:

  • 我想你的意思是写openOperation-&gt;Completed += ref new...bmpOp-&gt;Completed += ref new...

标签: c++ windows-runtime c++-cx ppl iasyncoperation


【解决方案1】:

我想你的意思是写 openOperation-&gt;Completed += ref new...bmpOp-&gt;Completed += ref new...。我不是 C++ 专家,但据我所知 - 异步操作通常包含在 create_task 调用中。不太清楚为什么 - 也许是为了避免在不取消订阅的情况下订阅事件?

我觉得大致应该是这样的:

auto bmp = ref new BitmapImage();

create_task(storageImageFile->OpenAsync(FileAccessMode::Read)) // get the stream
    .then([bmp](IRandomAccessStream^ ^stream) // continuation lambda
{
    return create_task(bmp->SetSourceAsync(stream)); // needs to run on ASTA/Dispatcher thread
}, task_continuation_context::use_current()) // run on ASTA/Dispatcher thread
    .then([bmp]() // continuation lambda
{
        UINT32 imageWidth = (UINT32)bmp->PixelWidth; // needs to run on ASTA/Dispatcher thread
        UINT32 imageHeight = (UINT32)bmp->PixelHeight; // needs to run on ASTA/Dispatcher thread

        // TODO: use imageWidth and imageHeight
}, task_continuation_context::use_current()); // run on ASTA/Dispatcher thread

【讨论】:

  • 非常感谢。我对 ppl 任务和并发任务知之甚少。只是为了一点建议,我应该在异步函数返回 IAsyncOperation 时使用 create_task(),并在异步函数返回 IAsyncAction 时使用 task_continuation_context::use_current() 来捕获返回值。对吗?
  • create_taskIAsyncOperation 包装在一个可以继续的任务中。 .then(lambda, task_continuation_context::use_current()) 使 lambda 在您触摸 UI 对象时需要的 UI 线程上运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-11
  • 1970-01-01
  • 2013-03-13
  • 2013-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多