diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index d03debf3fc..52ff515b0b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -265,7 +265,7 @@ namespace Microsoft.PowerShell.Commands { if (readTimeout == Timeout.InfiniteTimeSpan) { - return await stream.ReadAsync(buffer, cancellationToken); + return await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); } using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); @@ -292,7 +292,7 @@ namespace Microsoft.PowerShell.Commands if (perReadTimeout == Timeout.InfiniteTimeSpan) { // No timeout - use fast path - await source.CopyToAsync(destination, cancellationToken); + await source.CopyToAsync(destination, cancellationToken).ConfigureAwait(false); return; } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 index c9de423696..bb283b5795 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/WebCmdlets.Tests.ps1 @@ -4600,3 +4600,34 @@ Describe 'Invoke-WebRequest and Invoke-RestMethod support OperationTimeoutSecond RunWithNetworkTimeout -Command Invoke-RestMethod -Uri $uri -OperationTimeoutSeconds 2 -WillTimeout -Arguments '-SkipCertificateCheck' } } + + +Describe "Invoke-RestMethod should run in the default synchronization context (threadpool)" -Tag "CI" { + BeforeAll { + $oldProgress = $ProgressPreference + $ProgressPreference = 'SilentlyContinue' + $WebListener = Start-WebListener + } + + AfterAll { + $ProgressPreference = $oldProgress + } + + It "Invoke-RestMethod works after constructing a WindowsForm object" -Skip:(!$IsWindows) { + $env:URI_TO_TEST = Get-WebListenerUrl -Test 'Get' + $irmResult = $null + try { + $pwsh = Join-Path $PSHOME "pwsh" + $irmResult = & $pwsh -NoProfile { + Add-Type -AssemblyName System.Windows.Forms + $null = New-Object System.Windows.Forms.Form + Invoke-RestMethod $env:URI_TO_TEST + } + } finally { + $env:URI_TO_TEST = $null + } + + # Simply making it this far is good enough to ensure we didn't hit a deadlock + $irmResult | Should -Not -BeNullOrEmpty + } +}