Skip to content

Conversation

mconnew
Copy link
Member

@mconnew mconnew commented Apr 5, 2023

Fix Heartbeat logging after disposal

Prevent Heartbeat from logging exceptions after disposal.
Fix timer loop so disposal check is immediately before heartbeat execution.

Description

During CoreWCF (based on aspnetcore) unit tests we have an ILogger built on ITestOutputHelper which will abort the test run if something is logged after the test has completed execution. The Heartbeat class can log after Dispose() has been called, which means our test run is getting aborted.

This change fixes 2 issues. First, the existing implementation called Thread.Sleep between the disposal check and calling the heart beat handlers which means the handlers can easily get called after the host has been stopped. Then in the handler code, if there's an exception it would always log even if it was disposed.

Fixes #47577

…op so disposal check is immediately before heartbeat execution
}
}

private void TimerLoop()
{
Thread.Sleep(_interval);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added an initial Thread.Sleep before the timer loop to avoid a potential breaking change. The previous code guaranteed a Thread.Sleep call before the first invocation of OnHeatbeat. I wanted to avoid the possibility of any latent issues of a heartbeat handler failing if called too soon. This change maintains this behavior.

@JamesNK
Copy link
Member

JamesNK commented Apr 5, 2023

Seems ok to me.

Off-topic to PR but related to this area: It seems wasteful that the heartbeat thread can sleep for 5 seconds 1 second after the app is stopped. Thread.Sleep can't be canceled. Instead, have we considered using a WaitHandle that can be triggered on stop to exit the TimerLoop immediately?

@halter73 @Tratcher @BrennanConroy

@mconnew
Copy link
Member Author

mconnew commented Apr 6, 2023

Isn't it only 1 second?

@danmoseley
Copy link
Member

Thread.Sleep can't be canceled.

I put this in the other issue but I believe Thread.Interrupt will cancel it. Of course you have to have the thread object.

@JamesNK JamesNK merged commit 1a24b04 into main Apr 10, 2023
@JamesNK JamesNK deleted the FixHeartbeatTimerLoop branch April 10, 2023 06:56
@ghost ghost added this to the 8.0-preview4 milestone Apr 10, 2023
@amcasey amcasey added area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions and removed area-runtime labels Jun 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Heartbeat.TimerLoop continues running after WebHost stopped and disposed
4 participants