简体   繁体   English

如何防止用户管理器死锁?

[英]How to prevent Deadlock with Usermanager?

I have a registration page on blazor (server).我在 blazor(服务器)上有一个注册页面。 On that Page I want to implement a register function using AspnetCor.Identity在该页面上,我想使用 AspnetCor.Identity 实现注册功能

This is the Method: (_usermanager is of type AspNetCore.Identity.UserManager<>)这是方法:(_usermanager 的类型为 AspNetCore.Identity.UserManager<>)

  public bool Register(RegisterUser regUser)
    {
        var newUser = new ApplicationUser { Email = regUser.Mail, UserName = regUser.Mail};           
        var sd= _userManager.CreateAsync(newUser, "password").Result;
        if (!sd.Succeeded)
        {                
            return false;
        }
        return true;
    }

The method is called from within HandleValidSubmit on the blazor-page:该方法是从 blazor-page 上的 HandleValidSubmit 中调用的:

<EditForm Model="@_registerUser" OnValidSubmit="HandleValidSubmit">
//...
</EditForm>
@code {
      private void HandleValidSubmit()
        {
            if (identity.Register(_registerUser)) {
              NaviationManager.NavigateTo($"/manage/registersent");
            }
        }
}

When Registration fails it works just as designed returning false.当注册失败时,它会按设计返回 false。 But when registration would be fine I end up in a Deadlock at _userManager.CreateAsync(newUser, "password").Result;但是当注册没问题时,我最终陷入了_userManager.CreateAsync(newUser, "password").Result;的死锁_userManager.CreateAsync(newUser, "password").Result;

When I do not try to make the async-call synchronous and replace the call by _userManager.CreateAsync(newUser, "password") (and simply ignore any return value) the user gets created without an issue.当我不尝试使异步调用同步并用_userManager.CreateAsync(newUser, "password")替换调用时(并简单地忽略任何返回值),用户创建时没有问题。

How should I handle an async-call with return-value from within HandleValidSubmit ?我应该如何处理与返回值从内异步调用HandleValidSubmit

Make everything async - returning Task s and await ing them as appropriate.使所有内容async - 返回Task并根据需要await它们。 Don't call .Result or .Success .不要调用.Result.Success Let the compiler help you write better async code.让编译器帮助您编写更好的异步代码。

For instance make HandleValidSubmit async.例如使HandleValidSubmit异步。

private async void HandleValidSubmit()
{
    if (await identity.RegisterAsync(_registerUser)) 
    {
        NaviationManager.NavigateTo($"/manage/registersent");
    }
}

async void should be only used for event-type things since they are akin to "fire and forget". async void应该仅用于事件类型的事物,因为它们类似于“即发即弃”。

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

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