After 2 years of experience with Blazor, i figured that the only reliable way to pass an CancellationToken
to a Task within an Object of a longer Lifetime (e.g. Singleton or Scoped Service) is the combination of IDisposeable
and CancellationTokenSource
@page "/"
@implements IDisposable
*@ Razor Stuff *@
@code
{
private CancellationTokenSource _cts = new();
protected override async Task OnInitializedAsync()
{
await BusinessLogicSingleton.DoExpensiveTask(_cts.Token);
}
#region IDisposable
public void Dispose()
{
_cts.Cancel();
_cts.Dispose();
}
#endregion
}
如果一再使用或只是为了遵守《德国-德国-德国规则》,你也可以继承<>编码>ComponentBase。 班级,然后使用这一级,用于需要通过<代码>的部件 编号:
public class CancellableComponent : ComponentBase, IDisposable
{
internal CancellationTokenSource _cts = new();
public void Dispose()
{
_cts.Cancel();
_cts.Dispose();
}
}
@page "/"
@inherits CancellableComponent
@* Rest of the Component *@
我还发现,虽然你可以删除<代码>。 缩略语 HttpContext.RequestAborted token, which is the same that will have andjectioned in their ASP. Net MVC 现行<代码>方法要求。 净额6编码> 版本将never,即使在与客户的联系被切断后,也可处理>。
This may be a case for the Developer-Team on Github as i do see UseCases for it where the User is allowed to exit the Component while the Task keeps on going until the User leaves the Website completely.
(For such cases, my recommended Workaround would be to write your own CircuitHandler
that will give you Events for when a Circuit is removed.)