Replies: 2 comments 2 replies
-
Hi there, public class BackgroundTaskManager : IDisposable
{
private readonly Dictionary<string, CancellationTokenSource> _tasks = new Dictionary<string, CancellationTokenSource>();
public void StartTask(string circuitId, Action<CancellationToken> task)
{
var cts = new CancellationTokenSource();
_tasks[circuitId] = cts;
Task.Run(() => task(cts.Token), cts.Token);
}
public void StopTask(string circuitId)
{
if (_tasks.TryGetValue(circuitId, out var cts))
{
cts.Cancel();
_tasks.Remove(circuitId);
}
}
public void Dispose()
{
foreach (var cts in _tasks.Values)
{
cts.Cancel();
}
}
} next inject into your page: @page "/background-example"
@inject BackgroundTaskManager TaskManager
<h3>Background Task Example</h3>
<button @onclick="StartBackgroundTask">Start Task</button>
<button @onclick="StopBackgroundTask">Stop Task</button>
@code {
private string _circuitId;
protected override async Task OnInitializedAsync()
{
_circuitId = GetCircuitId();
await base.OnInitializedAsync();
}
private string GetCircuitId()
{
return Context.CircuitId;
}
private void StartBackgroundTask()
{
TaskManager.StartTask(_circuitId, token =>
{
while (!token.IsCancellationRequested)
{
// work here ...
}
});
}
private void StopBackgroundTask()
{
TaskManager.StopTask(_circuitId);
}
public override async Task DisposeAsync()
{
TaskManager.StopTask(_circuitId);
await base.DisposeAsync();
}
} next handle circuit disconnects to clean up any resources or tasks associated with that circuit: public class MyCircuitHandler : CircuitHandler
{
private readonly BackgroundTaskManager _taskManager;
public MyCircuitHandler(BackgroundTaskManager taskManager)
{
_taskManager = taskManager;
}
public override Task OnCircuitClosedAsync(Circuit circuit, CancellationToken cancellationToken)
{
_taskManager.StopTask(circuit.Id);
return base.OnCircuitClosedAsync(circuit, cancellationToken);
}
} Remeber to register the circuit handler: public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<BackgroundTaskManager>();
services.AddScoped<CircuitHandler, MyCircuitHandler>();
} |
Beta Was this translation helpful? Give feedback.
-
Yes its a sample, you can try to read the CircuitId with a custom handler that add and remove a circuit, than access the CircuitId from the page. |
Beta Was this translation helpful? Give feedback.
-
My blazor server app creates background threads (to refresh the grids). but the problem is after client disconnects, those threads created by that user session still kept running. There seems no way to get the current circuits id (from a .razor code file).
Beta Was this translation helpful? Give feedback.
All reactions