Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[3.x] Fix potential grain timer deadlock during disposal #8949

Merged
merged 1 commit into from
Apr 23, 2024

Conversation

ReubenBond
Copy link
Member

@ReubenBond ReubenBond commented Apr 20, 2024

Fixes #7865

To prevent the deadlock, we yield before invoking the timer callback. See comment.

Microsoft Reviewers: Open in CodeFlow

{
// This is called under a lock, so ensure that the method yields before invoking a callback
// which could take a different lock and potentially cause a deadlock.
await Task.Yield();
Copy link
Member Author

Choose a reason for hiding this comment

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

This is the crux of the fix: under the lock, we forward the call to this method, which immediately yields, releasing the lock before the callback is invoked. This way, the callback will not be invoked under the lock and the potential for a deadlock is eliminated.

}

private void DisposeTimer()
{
var tmp = timer;
if (tmp == null) return;
var asyncTimer = Interlocked.CompareExchange(ref timer, null, timer);
Copy link
Member Author

Choose a reason for hiding this comment

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

Rather than taking a lock during disposal, we can use an interlocked operation. This allows us to atomically set the timer to null so that we can dispose it. Note that the existing code sets the timer to null outside of a lock anyway: the new version of the code uses timer is { IsStarted: true } instead of asyncCallback is null to check if the timer has been disposed.

@ReubenBond ReubenBond merged commit b77ce82 into dotnet:3.x Apr 23, 2024
12 checks passed
@ReubenBond ReubenBond deleted the fix/timer-deadlock branch April 29, 2024 14:38
@github-actions github-actions bot locked and limited conversation to collaborators May 30, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants