jondow
jondow

Reputation: 724

Blazor WebAssembly - Dispose not firing on browser close

I have blazor app running WASM (not server) on .NET 5, version 5.0.3. I would like to be able to detect when a user navigates away from the site or closes the browser. The dispose only seems to fire when navigating within the app itself (i.e. the page or control is disposed due to a navigation).

Here is my page markup, I have also tried implementing IAsyncDisposable with the same result:

@page "/"
@using Microsoft.AspNetCore.Authorization

@attribute [Authorize]

@inject NavigationManager NavigationManager
@inject IHubManager HubManager
@implements IDisposable

<Tabs />


@code{

        public void Dispose()
        {
            _ = HubManager.DisposeAsync();
        }
    }

According to some of the posts I have read here, this approach works when using the server version of blazor, can anyone tell me if there is another approach I need to use with WASM?

The goal is to be able to close / dispose a connection to my signalR hub at the point the user leaves the site.

Upvotes: 6

Views: 2830

Answers (1)

Lucky Brain
Lucky Brain

Reputation: 1751

The reason you can't hit a breakpoint while debugging is mentioned in the Blazor WebAssembly documentation here:

For now, you can't:

  • Break on unhandled exceptions.
  • Hit breakpoints during app startup before the debug proxy is running. This includes breakpoints in Program.cs and breakpoints in the OnInitialized{Async} lifecycle methods of components that are loaded by the first page requested from the app.
  • Debug in non-local scenarios (for example, Windows Subsystem for Linux (WSL) or Visual Studio Codespaces).
  • Automatically rebuild the backend Server app of a hosted Blazor WebAssembly solution during debugging, for example by running the app with dotnet watch run.

I guess component disposal is one of those scenarios even though it is not mentioned.

In these scenarios, what I do is just use the logger to log some lines or add some Console.WriteLine(...) and use the F12 tool console in the browser to see whether they were hit.

NOTE: This works for components while navigating around the entire Blazor site. As other members indicate, if you are closing the browser window, you won't be able to see anything in the F12 Tool as it is automatically closed.

Upvotes: 1

Related Questions