Skip to content

Instantly share code, notes, and snippets.

@altrive
Last active August 29, 2015 13:57
Show Gist options
  • Save altrive/9429486 to your computer and use it in GitHub Desktop.
Save altrive/9429486 to your computer and use it in GitHub Desktop.
param (
$RequestUrl = "http://127.0.0.1"
)
function Main
{
$ErrorActionPreference = "Stop"
Add-Type -AssemblyName System.Net.Http
#Reuse connection
$client = New-Object Net.Http.HttpClient
$hostName = (New-Object Uri($RequestUrl)).Host
$ipAddresses = [Net.Dns]::GetHostAddresses($hostName).IPAddressToString
#Show Connection Count
Write-Host ("Before: {0} connections" -f (Get-NetTCPConnection | where RemotePort -eq 80 | where { $_.RemoteAddress -in $ipAddresses }).Count)
#Case 1:Don't dispose HttpClient 
# Connect ⇒ Established(100 seconds) ⇒ TIME_WAIT(120seconds) ⇒ Closed
Invoke-HttpGetWithoutDispose -RequestUrl $RequestUrl > $null
Write-Host "-----------------Test1-----------------"
Write-Output (Get-NetTCPConnection | where RemotePort -eq 80 | where { $_.RemoteAddress -in $ipAddresses })
#Case 2:Dispose HttpClient
# Connect ⇒ TIME_WAIT(120seconds) ⇒ Closed
Invoke-HttpGetWithDispose -RequestUrl $RequestUrl > $null
Write-Host "-----------------Test2-----------------"
Write-Output (Get-NetTCPConnection | where RemotePort -eq 80 | where { $_.RemoteAddress -in $ipAddresses })
#Case 3:With Connection:Close header(Dont' call dispose)
# Connect ⇒ Closed
Invoke-HttpGetWithConnectionClose -RequestUrl $RequestUrl > $null
Write-Host "-----------------Test3-----------------"
Write-Output (Get-NetTCPConnection | where RemotePort -eq 80 | where { $_.RemoteAddress -in $ipAddresses })
#Report port status every 10 seconds(total 240 seconds)
$sw = [Diagnostics.Stopwatch]::StartNew()
#TODO: Use Timer callback to check status
foreach ($i in 0..24)
{
Write-Host ("-----------------Port status after {0:f1} seconds-----------------" -f ($sw.Elapsed.TotalSeconds))
Write-Output (Get-NetTCPConnection | where RemotePort -eq 80 | where { $_.RemoteAddress -in $ipAddresses })
sleep 10 #not exact delay
}
}
function Invoke-HttpGetWithoutDispose([string] $RequestUrl)
{
$client = New-Object Net.Http.HttpClient
$task = $client.GetAsync($RequestUrl)
$task.Wait()
return $task.Result
}
function Invoke-HttpGetWithDispose([string] $RequestUrl)
{
$client = New-Object Net.Http.HttpClient
$task = $client.GetAsync($RequestUrl)
$task.Wait()
$client.Dispose()
return $task.Result
}
function Invoke-HttpGetWithConnectionClose([string] $RequestUrl)
{
$client = New-Object Net.Http.HttpClient
$client.DefaultRequestHeaders.ConnectionClose = $true
$task = $client.GetAsync($RequestUrl)
$task.Wait()
#$client.Dispose() #Not Dispose
return $task.Result
}
Main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment