发生这种情况是因为您正在使用
i
变量
Action<>
.
但当您创建
Action
,但当任务完成时
我
具有价值
taskList.Count
(当
for
循环完成)。
只需向
对于
:
for (int i = 0; i < taskList.Count; i++)
{
var task = taskList[i];
var newSource = new TaskCompletionSource<Tuple<T, int>>();
taskSources.Add(newSource);
taskSourceList.Add(newSource);
int index = i; // <- add this variable.
task.ContinueWith(t =>
{
var source = taskSources.Take();
if (t.IsCanceled)
source.TrySetCanceled();
else if (t.IsFaulted)
source.TrySetException(t.Exception.InnerExceptions);
else if (t.IsCompleted)
source.TrySetResult(new Tuple<T, int>(t.Result, index));
}, CancellationToken.None, TaskContinuationOptions.PreferFairness, TaskScheduler.Default);
}
你可以读这个
question/answers
了解更多详细信息。