English 中文(简体)
取消 Token in Blazor pagess?
原标题:CancellationToken in Blazor Pages?

在满2年的岩石下生活之后,我现在在我的新的工作场所与Blazor打交道,在从事大部分工作之后,有许多工作要做。 NET Framework MVC prior to the 2 years.

在布茨or服务器方面,我试图运用我过去的知识,包括取消作为同业的象征性业务,而且我无法与布茨or一起找到大量有关这种业务的信息。

Are they still a Best Practice or did they became Obsolete at some point? I did found this previously asked question which recommends creating a tokensource on the OnInitializedAsync() method and cancelling it on Dispose() which i honestly find a bit crude. (I would need to implement this for each page and you know... DRY)

我还发现

In comparison, in asp.net Framework MVC i would build a Controller like this:

namespace SampleWebsite.Controllers
{
    public class SampleController : ApiController
    {
        private readonly MyEntities _entities = new MyEntities();

        public async Task<IHttpActionResult> MyAsyncApi(CancellationToken cancellationToken)
        {
            var result = _entities.MyModel.FirstOrDefault(e => e.Id == 1, cancellationToken: cancellationToken);
            return OK(result);
        }
    }
}

The CancellationToken will be injected by asp.net Framework / Core and is directly linked to the current context connection-pipe. Hence, if the user closes the connection, the token becomes invalid.

我本会认为,如果依赖注射是其中的一大部分,就算是纸面和空白,这里的情况也是这样,但不能在此找到任何有关文件。

So, should cancellationtokens still be used at this point or does Microsoft do some magic in the background for asynchronous tasks? And if yes, what would be the best implementation?

EDIT: Here would be my Setup to clarify:

Blazor-Component:

@page "/Index"
@inject IIndexService Service

@* Some fancy UI stuff *@

@code {
    private IEnumerable<FancyUiValue> _uiValues;

    protected override async Task OnInitializedAsync()
    {
        _uiValues = await Service.FetchCostlyValues();
    }
}

而那些进行重提的意外服务公司:

public interface IIndexService
{
    Task<IEnumerable<FancyUiValue>> FetchCostlyValues();
}

public class IndexService : IIndexService
{
    public async Task<IEnumerable<FancyUiValue>> FetchCostlyValues()
    {
        var uiValues = await heavyTask.ToListAsync(); // <-- Best way to get a cancellationtoken here?
        return uiValues;
    }
}

我的问题是,在守则的具体部分中打脚石的最佳途径是什么,或者由于服务器在连接(例如)结束时将杀死所有运行任务,这是否无关紧要?

最佳回答

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.)

问题回答

不是将<条码>代码>按人工方式添加到所有组成部分的,你可以形成一个基础组成部分,暴露<条码>的票标/代码>,并在<>项目的所有组成部分中自动使用这一基部分。

执行您的申请委员会

public abstract class ApplicationComponentBase: ComponentBase, IDisposable
{
    private CancellationTokenSource? cancellationTokenSource;

    protected CancellationToken CancellationToken => (cancellationTokenSource ??= new()).Token;

    public virtual void Dispose()
    {
        if (cancellationTokenSource != null)
        {
            cancellationTokenSource.Cancel();
            cancellationTokenSource.Dispose();
            cancellationTokenSource = null;
        }
    }
}

之后添加@inherits ApplicationComponentBase_Imports.razor 档案

网页:

await Task.Delay(50000, CancellationToken);

之后,你要求的任务将取消。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签