简体   繁体   English

如何制作 Blazor 页面互斥锁

[英]How to make a Blazor page mutex

I want to make it so one page of my Blazor app can function only once at the same time.我想让我的 Blazor 应用程序的一页只能同时运行一次。 Meaning when any user starts its functionality (it's working on our database) another won't be able to until all the work is finished, first.这意味着当任何用户开始其功能(它正在我们的数据库上工作)时,另一个用户将无法在所有工作完成之前,首先。

Kind of like locking / using a mutex.有点像锁定/使用互斥锁。

For shared state information, it's normal in Blazor to add a Singleton with Dependency Injection.对于共享状态信息,在 Blazor 中添加具有依赖注入的单例是正常的。 Warning this is not tested code, but you can get the idea.警告这不是经过测试的代码,但您可以理解。

Create a Singleton class:创建一个单例类:

public class LockState {
     public string UserId { get; set; }
}

Register it in Startup.csStartup.cs 中注册

public void ConfigureServices(IServiceCollection services){
    // . . .
    services.AddSingleton<LockState>();
}

Inject it into PageToLock.razor将其注入PageToLock.razor

@inject LockState LS
@inject AuthenticationStateProvider ASP

@if(LS.UserId == this.Userid){
    <YourDataBaseControl />
    <button @onclick="()=> this.UserId = null">X</button>
}
else {
    <div>The Database Control is Currently being used. . . </div>
}

@code {
    string UserId;
    protected override async Task OnInitializedAsync(){
        UserId = (await ASP.GetAuthenticationStateAsync()).User.FindFirst(c => c.Type.Contains("nameidentifier"))?.Value;
        if (LS.UserId is null) LS.UserId = this.UserId;
    }
}

Note that there's a problem.请注意,有问题。 When the user is done with the page, they have to set LS.UserId to null or it will be locked for all eternity.当用户完成页面时,他们必须将LS.UserId设置为 null,否则它将被永久锁定。 If they forget and just close the browser.如果他们忘记了,只需关闭浏览器。 . . . . that will be bad.那会很糟糕。 You'll have to figure out a reliable way to guarantee that the lock is removed.你必须想出一种可靠的方法来保证锁被移除。 You can add Timers to check if the circuit is still open, and should probably have an event so PageToLock.razor knows when the lock is removed.您可以添加计时器来检查电路是否仍然打开,并且可能应该有一个事件,以便PageToLock.razor知道锁何时被移除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM