@@ -530,10 +530,10 @@ protected override void Dispose(bool disposing)
530
530
base . Dispose ( disposing ) ;
531
531
}
532
532
533
- protected Task < HttpResponseMessage > SendAsync ( HttpMessageInvoker invoker , HttpRequestMessage request ) =>
533
+ protected Task < HttpResponseMessage > SendAsync ( HttpMessageInvoker invoker , HttpRequestMessage request , CancellationToken cancellationToken = default ) =>
534
534
TestHttpMessageInvoker ?
535
- invoker . SendAsync ( request , default ) :
536
- ( ( HttpClient ) invoker ) . SendAsync ( TestAsync , request ) ;
535
+ invoker . SendAsync ( request , cancellationToken ) :
536
+ ( ( HttpClient ) invoker ) . SendAsync ( TestAsync , request , cancellationToken ) ;
537
537
538
538
protected HttpMessageInvoker CreateHttpMessageInvoker ( HttpMessageHandler ? handler = null ) =>
539
539
TestHttpMessageInvoker ?
@@ -617,24 +617,32 @@ await Assert.ThrowsAsync<HttpRequestException>(async () =>
617
617
[ Fact ]
618
618
public async Task FailedRequests_ConnectionClosedWhileReceivingHeaders_Recorded ( )
619
619
{
620
- TimeSpan timeout = TimeSpan . FromSeconds ( 30 ) ;
620
+ using CancellationTokenSource cancelServerCts = new CancellationTokenSource ( ) ;
621
621
await LoopbackServerFactory . CreateClientAndServerAsync ( async uri =>
622
622
{
623
623
using HttpMessageInvoker client = CreateHttpMessageInvoker ( ) ;
624
624
using InstrumentRecorder < long > recorder = SetupInstrumentRecorder < long > ( InstrumentNames . FailedRequests ) ;
625
625
using HttpRequestMessage request = new ( HttpMethod . Get , uri ) { Version = UseVersion } ;
626
626
627
- await Assert . ThrowsAsync < HttpRequestException > ( async ( ) =>
627
+ Exception ex = await Assert . ThrowsAnyAsync < Exception > ( async ( ) =>
628
628
{
629
- using HttpResponseMessage response = await SendAsync ( client , request ) ;
630
- } ) . WaitAsync ( timeout ) ;
629
+ // Getting a cancellation is also good if we are unable to detect the peer shutdown.
630
+ using CancellationTokenSource cts = new CancellationTokenSource ( 10_000 ) ;
631
+ using HttpResponseMessage response = await SendAsync ( client , request , cts . Token ) ;
632
+ } ) ;
633
+ cancelServerCts . Cancel ( ) ;
634
+ Assert . True ( ex is HttpRequestException or TaskCanceledException ) ;
631
635
632
636
Measurement < long > m = recorder . GetMeasurements ( ) . Single ( ) ;
633
637
VerifyFailedRequests ( m , 1 , uri , null , null ) ;
634
638
} , async server =>
635
639
{
636
- var connection = ( LoopbackServer . Connection ) await server . EstablishGenericConnectionAsync ( ) . WaitAsync ( timeout ) ;
637
- connection . Socket . Close ( ) ;
640
+ try
641
+ {
642
+ var connection = ( LoopbackServer . Connection ) await server . EstablishGenericConnectionAsync ( ) . WaitAsync ( cancelServerCts . Token ) ;
643
+ connection . Socket . Close ( ) ;
644
+ }
645
+ catch { }
638
646
} ) ;
639
647
}
640
648
}
0 commit comments