question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

EventHandler Leak?

See original GitHub issue

First I wanted to say thank you for sharing. It’s a really cool class. I love that it’s simple but also pretty powerful.

Question:

Is there an EventHandler leak here (I think there is unless Dispose is unwiring that event)? Even though the _timer is Disposed of I think the EventHandler still needs to be unsubscribed from before that (not sure how to do that with a lambda, my solution was to make the event handler it’s own function that way I could unsubscribe from it -= MyEvent before Dispose was called).

// This needs to be unsubscribed from before _timer is disposed.
_timer.Elapsed += async (sender, args) =>

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
christianmorantecommented, Apr 8, 2022

Thanks for your time @blakepell. It is just when closing the lambda function that is to say that the exception may be occurring inside or in the recursion. image

Sorry for my dirty code. And of course I have severals jobs working with different scheduling

0reactions
blakepellcommented, Apr 8, 2022

@Changhui Xu That’s awesome, didn’t realize it did cleaned that event up for me (I’ve been manually doing it for years, hehe).

@christianmorante I haven’t received any weird null exception errors yet but I will keep an eye out (I have a .NET 6 site, it’s in memory 24/7 and I’m using this to run some database cleanup code in the middle of the night). I shuffled some code around also though when I mistakenly thought it was leaking the event handler so mine looks like below. My first thought of what to look for is a race condition, what happens if it’s running Elapsed maybe for a long running time… e.g. the object is disposed in it’s own elapsed, the DoWork takes a long time and the garbage collector comes after it in the interim because it was disposed of. I’m not sure how C# behaves in that scenario or if there’s a difference in that case between the lambda in this library or how I changed it by having it as it’s own function.

What value is it saying is null on your line 62 in BaseServiceWorker?

protected virtual async Task ScheduleJob(CancellationToken cancellationToken)
{
    var next = _expression.GetNextOccurrence(DateTimeOffset.Now, _timeZoneInfo);

    if (!next.HasValue)
    {
        return;
    }

    var delay = next.Value - DateTimeOffset.Now;

    // Prevent non-positive values from being passed into Timer
    if (delay.TotalMilliseconds <= 0)
    {
        await ScheduleJob(_cancellationToken);
    }

    _timer = new Timer(delay.TotalMilliseconds);
    _timer.Elapsed += Elapsed;
    _timer.Start();
}

private async void Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
{
    if (_timer != null)
    {
        _timer.Elapsed -= Elapsed;
        _timer.Dispose();
        _timer = null;
    }

    if (!_cancellationToken.IsCancellationRequested)
    {
        await DoWork(_cancellationToken);
    }

    if (!_cancellationToken.IsCancellationRequested)
    {
        await ScheduleJob(_cancellationToken); // Reschedule next
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Why and How to avoid Event Handler memory leaks?
The cause is simple to explain: while an event handler is subscribed, ... You can avoid such a leak by detaching the event...
Read more >
Are you afraid of event handlers because of C# memory ...
At some places, the idea of memory leak became so scary that some developers get paranoid about any event handler code they see...
Read more >
5 Techniques to avoid Memory Leaks by Events in C# .NET ...
1. Make sure to Unsubscribe · 2. Have handlers that unsubscribe themselves · 3. Use Weak Events with Event Aggregator · 4. Use...
Read more >
Diagnosing Event Handler Leaks with the Memory Usage ...
Using the Memory Usage tool, we can not only discover the leaks, but also track down the references that are keeping the zombies...
Read more >
Understanding and Avoiding Memory Leaks with Event ...
If you subscribe to an event in C# and forget to unsubscribe, does it cause a memory leak? Always? Never? Or only in...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found