DelphiNewbie
DelphiNewbie

Reputation: 57

Do I need to dispose of a handler on a static class?

I have a Blazor server-side app, which includes a static class. Don't think Blazor is specifically relevant, but mentioned it in case.

My components use methods on this class to handle events...

  protected override async Task OnInitializedAsync() {
    MyStaticClass.Event += data => {
      // Do stuff with data
    };
  }

I'm not sure what happens when the Blazor component is torn down. Does the subscription remain (causing a memory leak) or not?

According to the Microsoft docs...

When anonymous functions, methods, or expressions, are used, it isn't necessary to implement IDisposable and unsubscribe delegates. However, failing to unsubscribe a delegate is a problem when the object exposing the event outlives the lifetime of the component registering the delegate. When this occurs, a memory leak results because the registered delegate keeps the original object alive.

However, that specifies "the object exposing the event," which is fine when you have an object, but in my case, I have a static class, not an object.

My feeling is that I would still need to implement IDisposable, as the static class has a reference to the subscriber's event handler, but I'm not sure if this is right.

Can anyone clarify this for me?

Upvotes: 0

Views: 51

Answers (0)

Related Questions