-
-
Save aldrichtr/52b9c98d2b428af95b389536fbfa887b to your computer and use it in GitHub Desktop.
"Await" one or more tasks in PowerShell in a cancellable manner (e.g. ctrl-c still works)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace System.Threading.Tasks | |
using namespace System.Collections.Generic | |
filter Receive-Task { | |
#Wait on one or more tasks in a cancellable manner | |
[CmdletBinding()] | |
param( | |
[parameter(Mandatory, ValueFromPipeline)][Task]$Task, | |
#How long to wait before checking for a cancellation in milliseconds | |
[int]$WaitInterval = 500 | |
) | |
begin { | |
[List[Task]]$Tasks = @() | |
} | |
process { | |
$Tasks.Add($Task) | |
} | |
end { | |
while ($Tasks.count -gt 0) { | |
$completedTaskIndex = [Task]::WaitAny($Tasks, $WaitInterval) | |
if ($completedTaskIndex -eq -1) { | |
#Timeout occured, this provides an opportunity to cancel before waiting again | |
continue | |
} | |
$completedTask = $Tasks[$completedTaskIndex] | |
$Tasks.RemoveAt($completedTaskIndex) | |
#We use this instead of .Result so we get a proper exception if one was thrown instead of AggregateException | |
#Reference: https://stackoverflow.com/questions/17284517/is-task-result-the-same-as-getawaiter-getresult/38530225#38530225 | |
$completedTask.GetAwaiter().GetResult() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment