Last active
May 2, 2025 08:11
-
-
Save scriptingstudio/9d50c6d728d490eea6694af71514681a to your computer and use it in GitHub Desktop.
Simple await function to wait for an async task to complete within timeout and return the result if any
This file contains hidden or 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
| function Wait-Task { | |
| param ( | |
| [Parameter(Mandatory, ValueFromPipeline)] | |
| [System.Threading.Tasks.Task] $Task, | |
| [alias('wait')][int] $TimeOutMs = 1000 | |
| ) | |
| begin {if ($TimeOutMs -lt 1) {$TimeOutMs = -1}} | |
| process { | |
| if ($task.AsyncWaitHandle.WaitOne($timeoutMs)) { | |
| $task.GetAwaiter().GetResult() | |
| } | |
| } | |
| } # END Wait-Task | |
| filter Wait-Task ([alias('wait')][int]$TimeOutMs = 1000) { | |
| if ($timeoutMs -lt 1) {$timeoutMs = -1} | |
| if ($_.AsyncWaitHandle.WaitOne($timeoutMs)) {$_.GetAwaiter().GetResult()} | |
| } # END Wait-Task | |
| # example | |
| $webclient = [System.Net.Webclient]::New() | |
| $webclient.DownloadStringTaskAsync('https://docs.microsoft.com/en-us/windows/release-health/windows11-release-information') | | |
| Wait-Task -wait 400 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment