我必須修改以下代碼。我已經給出了一個任務串列(httpClient.Run 方法回傳任務)。我必須運行它們并等待它們全部完成。稍后我需要收集所有結果并建立回應。
var tasks = new Dictionary<string, Task<string>>();
tasks.Add("CODE1", service.RunTask("CODE1"));
tasks.Add("CODE2", service.RunTask("CODE2"));
tasks.Add("CODE3", service.RunTask("CODE3"));
//...
var result = await Task.WhenAll(tasks.Values); // how to get CODE (dictionary KEY) here
// build response
上面的問題是,當我們得到時,results我們丟失了運行的確切任務。results 是字串陣列,但我需要,例如,KeyValuePair array. 我們需要知道運行了哪個任務(CODE),這樣我們才能正確構建結果。
uj5u.com熱心網友回復:
您可以async在 Select lambda 中使用將KeyValuePair<T1, Task<T2>s 轉換為Task<KeyValuePair<T1, T2>>s。
var resultTasks = tasks.Select(async pair => KeyValuePair.Create(pair.Key, await pair.Value));
IReadOnlyCollection<KeyValuePair<string, string>> results = await Task.WhenAll(resultTasks);
uj5u.com熱心網友回復:
像這樣的事情應該這樣做。這是假設你Task.WhenAll()先打電話的情況下寫的。否則,當您開始列舉 over 時,您將阻塞執行緒resultsWithKeys。
await Task.WhenAll(tasks.Values());
var resultsWithKeys = tasks.Select(
x => new
{
Key = x.Key,
Result = x.Value.Result
});
foreach (var result in resultsWithKeys)
Console.WriteLine($"{result.Key} - {result.Result.SomeValue}");
uj5u.com熱心網友回復:
Dictionary<string, Task<string>>包含不將密鑰作為其一部分傳播的任務Result。如果您希望任務在其結果中包含鍵,則必須創建一個新字典并用包裝現有任務的新任務填充它。這些TResult新任務中的 可以是您選擇的結構,例如KeyValuePair<string, string>. 下面是一個擴展方法WithKeys,它允許使用新任務輕松創建新字典:
public static Dictionary<TKey, Task<KeyValuePair<TKey, TValue>>> WithKeys<TKey, TValue>(
this Dictionary<TKey, Task<TValue>> source)
{
return source.ToDictionary(e => e.Key,
async e => KeyValuePair.Create(e.Key, await e.Value.ConfigureAwait(false)),
source.Comparer);
}
使用示例:
KeyValuePair<string, string>[] result = await Task.WhenAll(tasks.WithKeys().Values);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/452581.html
