如何重构使用PPL的代码。 C ++

时间:2017-08-03 16:11:13

标签: c++ asynchronous refactoring task ppl

所以我的功能看起来像这样

task<shared_ptr<myObjectsResult>> task1 = create_task([this,token, stream]
{
    // Here I have code that is working, but I would like to refactor it
    // maybe even make it go after or before this surrounding task.

    create_task(BitmapDecoder::CreateAsync(stream)).then([this, token]
    (BitmapDecoder^ bitmapDecoder)
    {
        create_task(bitmapDecoder->GetSoftwareBitmapAsync()).then([this, token]
        (SoftwareBitmap^ softwareBitmap)
        {
            OcrEngine^ ocrEngine = OcrEngine::TryCreateFromUserProfileLanguages();
            if (ocrEngine != nullptr)
            {
                create_task(ocrEngine->RecognizeAsync(softwareBitmap)).then([fileInfo, this, transactionPriority, token]
                (OcrResult^ ocrResult)
                {
                    doSomethingWithText(OcrResult->Text->Data());
                });
            }
        });
     });
    ...
    return runAsyncFunctionThatReturnsMyObjectResultTask(token);
});

它的工作原理很好,但是我想把OCR逻辑移到这里不在的代码的其他部分,但是我想从这里调用它。 我试过的是创造

task<OcrResult^> GetOCRTextFromStream(_In_ IRandomAccessStream^ stream)
{
    create_task(BitmapDecoder::CreateAsync(stream)).then([]
    (BitmapDecoder^ bitmapDecoder)
    {
         create_task(bitmapDecoder->GetSoftwareBitmapAsync()).then([]
         (SoftwareBitmap^ softwareBitmap)
         {
             OcrEngine^ ocrEngine = OcrEngine::TryCreateFromUserProfileLanguages();
         if (ocrEngine != nullptr)
         {
              return create_task(ocrEngine->RecognizeAsync(softwareBitmap));
         }
         else
         {
               OcrResult^ ocrResult = nullptr;
               return concurrency::task_from_result(ocrResult);
         }
     }
}

然后调用它。

GetOCRTextFromStream(stream).then([this, token]
(OcrResult^ ocrResult)
{
    doSomethingWithText(OcrResult->Text->Data());
}

当然这不起作用,但你得到了我想要的东西,我只是想重构这个,我只是无法理解如何做我想要的,如果它是可行的(我猜它是?)

谢谢大家,对不起,如果我的问题是nooby:)

1 个答案:

答案 0 :(得分:1)

这是C ++ / CX,解决方案是返回。

如果您只是在两个create_task前面添加返回

,这应该有效
return create_task([]
{
    return create_task([]
    {
    ...
    }
}