Skip to content

Commit e37a766

Browse files
Update ParallelLoopBuilder.cs (#2)
Bug fix
1 parent 61ad5a4 commit e37a766

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

src/ParallelLoopLibrary/ParallelLoopBuilder.cs

+10-3
Original file line numberDiff line numberDiff line change
@@ -648,12 +648,12 @@ private static async Task<Task> ToParallelLoopImplementation(
648648
}
649649

650650
// The only expected exception at this point is an OperationCanceledException,
651-
// originated from either the stoppingToken ot the cancelingToken.
651+
// originated from either the stoppingToken or the cancelingToken.
652652
var oce = ex as OperationCanceledException;
653653
if (oce != null)
654654
{
655655
if (oce.CancellationToken == cancelingToken)
656-
return Task.FromCanceled(oce.CancellationToken); // https://stackoverflow.com/questions/69552580/a-canceled-task-propagates-two-different-types-of-exceptions-depending-on-how-i
656+
return TaskFromCanceledSafe(oce.CancellationToken); // https://stackoverflow.com/questions/69552580/a-canceled-task-propagates-two-different-types-of-exceptions-depending-on-how-i
657657

658658
if (oce.CancellationToken == stoppingToken) return Task.CompletedTask;
659659
}
@@ -683,12 +683,19 @@ private static Task<object> CreateTask(ParallelLoopEntry entry, object argument,
683683
else // SyncAction & IsSynchronous
684684
{
685685
try { task = Task.FromResult(entry.SyncAction(argument)); }
686-
catch (OperationCanceledException oce) { task = Task.FromCanceled<object>(oce.CancellationToken); }
686+
catch (OperationCanceledException oce) { task = TaskFromCanceledSafe(oce.CancellationToken); }
687687
catch (Exception ex) { task = Task.FromException<object>(ex); }
688688
}
689689
return task;
690690
}
691691

692+
private static Task<object> TaskFromCanceledSafe(CancellationToken token)
693+
{
694+
var tcs = new TaskCompletionSource<object>();
695+
tcs.TrySetCanceled(token);
696+
return tcs.Task;
697+
}
698+
692699
private static Task<object> CanceledToFaultedConditional(Task<object> task,
693700
CancellationToken stoppingToken, CancellationToken cancelingToken)
694701
{

0 commit comments

Comments
 (0)