簡體   English   中英

如何從第一個任務中獲取結果然后在循環中使用 ContinueWith 將其傳遞給第二個任務?

[英]How to get result from 1st task then pass it to 2nd task using ContinueWith in a loop?

所以這就是我在做什么:

var resultObj = GetFirstResultAsync()
     .ContinueWith(t => GetSecondResultAsync(resultObj))
     .Wait();

本質上告訴我,我什至不能在變量聲明之前使用它,因此我得到了我發布的問題。 我該怎么做呢?

這是我的目標,我有一個列表resultObj然后在該列表上我將遍歷 Id 以獲取另一個列表的數組,我希望GetSecondResultAsync在列表上向下鑽取,我想使用異步因為它將使用HttpClient來獲取數據。

您應該能夠通過將 ContinueWith 語句更改為 t.Result 來傳遞結果。 就像是:

var resultObj = GetFirstResultAsync()
 .ContinueWith(t => GetSecondResultAsync(t.Result));

我還沒有測試代碼。

第一個運行的線程將返回一個“任務”。 您必須通過 Task.Result 訪問它。 這是您必須使用的。

編輯:如@fahadash 所述,不應使用“wait()”。 請改用“等待”。

使用ContinueWith創建一個結果類型不同於第一個任務的延續Task並不簡單。 您必須使用Unwrap方法來展平生成的Task<Task<MySecondResult>> ,小心處理失敗和取消情況,並明確指定將執行延續的TaskScheduler

Task<MySecondResult> task = GetFirstResultAsync().ContinueWith(t =>
{
    if (t.IsFaulted)
    {
        var tcs = new TaskCompletionSource<MySecondResult>();
        tcs.SetException(t.Exception.InnerExceptions);
        return tcs.Task;
    }
    if (t.IsCanceled)
    {
        TaskCompletionSource<MySecondResult> tcs = new();
        tcs.SetCanceled(new TaskCanceledException(t).CancellationToken);
        return tcs.Task;
    }
    return GetSecondResultAsync(t.Result);
}, TaskScheduler.Default).Unwrap();

這是相當麻煩的。 您不希望在您的應用程序代碼中頻繁出現這樣的代碼。 您可以將此功能封裝在擴展方法中,例如 GitHub 提案中請求的Then / ContinueWithResult擴展方法,或者使用async/await而不是ContinueWith Async/await 是可組合的,因此您可以編寫第三個async方法,將GetFirstResultAsyncGetSecondResultAsync為一個:

async Task<MySecondResult> GetSecondAfterFirstAsync()
{
    MyFirstResult result = await GetFirstResultAsync();
    return await GetSecondResultAsync(result);
}

暫無
暫無

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

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