As Mister Magoo pointed out, Circuit Handler is an effective way to solve this problem.
There is another way, which is based on more custom implementations of the Component base library. You can create an abstract class extending from the component base :
public abstract class CancellableComponentBase : ComponentBase, IDisposable
{
private CancellationTokenSource? _cancellationTokenSource;
protected CancellationToken ComponentDetached => (_cancellationTokenSource ??= new()).Token;
public virtual void Dispose()
{
if (_cancellationTokenSource != null)
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
_cancellationTokenSource = null;
}
}
}
In your _Imports.razor, you have to add:
@inherits CancellableComponentBase
This makes the default inherited class for ALL razor pages cancellable.
This allows you to call the ComponentDetached Cancellation token in your classes. IE:
<h3>Example</h3>
@code {
public void Bar()
{
Foo(ComponentDetached);
}
private void Foo(CancellationToken cts)
{
cts.Register(() => Console.WriteLine("page closed"));
}
}
When this page is closed, The delegate calling the console write line will be called.
Edit: Source that helped me out here: https://www.meziantou.net/canceling-background-tasks-when-a-user-navigates-away-from-a-blazor-component.htm
OnDisconnectedAsync
handler does not work for you? – Saintebeuve