Skip to content

Commit

Permalink
Fix NullReferenceException in Timer disposal (#5321)
Browse files Browse the repository at this point in the history
Protect against `NullReferenceException` when disposing of `Timer`.
Resolves #5316.
  • Loading branch information
martincostello authored Aug 2, 2024
1 parent f68108e commit 68a79b5
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/Libraries/Microsoft.Extensions.TimeProvider.Testing/Timer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,18 @@ public bool Change(TimeSpan dueTime, TimeSpan period)
_ = Throw.IfOutOfRange(periodMs, -1, MaxSupportedTimeout, nameof(period));
#pragma warning restore S3236 // Caller information arguments should not be provided explicitly

if (_timeProvider == null)
var timeProvider = _timeProvider;
if (timeProvider is null)
{
// timer has been disposed
return false;
}

if (_waiter != null)
var waiter = _waiter;
if (waiter is not null)
{
// remove any previous waiter
_timeProvider.RemoveWaiter(_waiter);
timeProvider.RemoveWaiter(waiter);
_waiter = null;
}

Expand All @@ -62,8 +64,8 @@ public bool Change(TimeSpan dueTime, TimeSpan period)
period = TimeSpan.Zero;
}

_waiter = new Waiter(_callback!, _state, period.Ticks);
_timeProvider.AddWaiter(_waiter, dueTime.Ticks);
_waiter = waiter = new Waiter(_callback!, _state, period.Ticks);
timeProvider.AddWaiter(waiter, dueTime.Ticks);
return true;
}

Expand All @@ -89,9 +91,10 @@ public ValueTask DisposeAsync()

private void Dispose(bool _)
{
if (_waiter != null)
var waiter = _waiter;
if (waiter is not null)
{
_timeProvider!.RemoveWaiter(_waiter);
_timeProvider?.RemoveWaiter(waiter);
_waiter = null;
}

Expand Down

0 comments on commit 68a79b5

Please sign in to comment.