簡體   English   中英

等待一系列連續任務完成

[英]wait for a series of continuous tasks to finish

template<class T>T MainPage::addSubtract(T num1, T num2,boolean add){
T result;
task<T> t( [num1, num2, add,result]()->T{
    if (num1 < 0 || num2 < 0){
        throw ref new Exception(-1, "Invalid Arguments");
    }
    else{
        if (add){
            OutputDebugString(num1.ToString()->Data());
            OutputDebugString(L"\n");
            OutputDebugString(num2.ToString()->Data());
            return num1 + num2;
        }
        else{
            return num1 - num2;
        }
    }
});
t .then([result](task<T> t)mutable->T{
    try{
        //T result;
        OutputDebugString(L"REsult= ");
        result = t.get();
        OutputDebugString(result.ToString()->Data());
        //this->resultTextBlock->Text = result.ToString();
        return result;
    }
    catch (Exception^ e){
        OutputDebugString(L"Exception encountered");
        return -1;
    }
});
return result;

}

我在第二個任務結束時嘗試了wait()和get(),但沒有成功(拋出未處理的異常) An invalid parameter was passed to a function that considers invalid parameters fatal. 我要做的是僅在兩個任務都完成執行后才返回結果。

發生錯誤是因為您返回了result ,但從未分配給它。 無法使用默認構造的任務。

在這里,錯誤讓您知道自己犯了一個錯誤。 完成實際工作的任務是t ,但您沒有返回該值。

您在繼續任務中也遇到了問題。 調用t.then(...)創建一個依賴於t的新任務,但您並未將該調用的結果分配給任何對象。 返回值剛剛丟失。

因此,即使您返回t而不是result ,客戶端代碼也永遠不會知道您在那里有一個延續。

而是,再次分配:

t = t.then(...

甚至更好,可以在第一個任務之后直接鏈接呼叫。

return create_task([=] { 
    ... 
}).then([=](task<T> result) {
    ...        
});

請注意,返回的內容是對then()的調用的結果。 那就是任務鏈的結尾,這可能就是您要在客戶端代碼中等待的意思。

另一個注意事項:通常,您只可以接受延續中的T值,而不是task<T> 異常和取消將按預期傳播。

return create_task([=] { 
    ... 
}).then([=](T result) {
    ...        
});

現在,如果第一個任務失敗或被取消,那么then()中指定的繼續將不會運行。 並且這也傳播到該方法的客戶端代碼。

以我的經驗,當您想詳細觀察和區分成功/失敗/取消(例如打印調試消息)時,將task<T>作為參數非常有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM