ThreadPool.QueueUserWorkItem 的 .NET Core 替代品

2023-12-26

我正在努力实现 ForgotPassword 功能,即在 AccountController 中使用 ASP.NET Identity,如标准 VS 2015 项目模板中所示。

我试图解决的问题是,当发送密码重置电子邮件时,页面响应有明显的延迟。如果密码恢复尝试未找到现有帐户,则不会发送电子邮件,因此响应速度更快。所以我认为这种明显的延迟可以用于账户枚举,即黑客可以根据忘记密码页面的响应时间来确定账户是否存在。

因此,我想消除页面响应时间的这种差异,以便无法检测是否找到帐户。

过去,我曾使用如下代码对可能较慢的任务进行排队,例如将电子邮件发送到后台线程:

ThreadPool.QueueUserWorkItem(new WaitCallback(AccountNotification.SendPasswordResetLink), 
notificationInfo);

但 .NET Core 中不存在 ThreadPool.QueueUserWorkItem,因此我需要一些替代方案。

我想一个想法是在 Thread.Sleep 找不到帐户的情况下引入人为延迟,但我宁愿找到一种在不阻塞 UI 的情况下发送电子邮件的方法。

更新:为了澄清问题,我发布了实际代码:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{   
    if (ModelState.IsValid)
    {
    var user = await userManager.FindByNameAsync(model.Email);
    if (user == null || !(await userManager.IsEmailConfirmedAsync(user)))
    {
        // Don't reveal that the user does not exist or is not confirmed
        return View("ForgotPasswordConfirmation");
    }

    var code = await userManager.GeneratePasswordResetTokenAsync(user);
    var resetUrl = Url.Action("ResetPassword", "Account", 
        new { userId = user.Id, code = code }, 
        protocol: HttpContext.Request.Scheme);

    //there is a noticeable delay in the UI here because we are awaiting
    await emailSender.SendPasswordResetEmailAsync(
    userManager.Site,
    model.Email,
    "Reset Password",
    resetUrl);


        return View("ForgotPasswordConfirmation");
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

有没有一种好的方法可以使用其他内置框架功能来处理这个问题?


只是不要等待任务。这基本上相当于在线程池上运行所有代码来开始,假设它不会在内部等待任何东西而不调用ConfigureAwait(false)。 (如果这是您的代码,您需要检查一下。)

You might想要将任务添加到服务器关闭之前应等待的一组任务中,假设 ASP.NET 中有一些适当的“请求关闭”概念。这是值得研究的,并且可以防止由于服务器在发送响应后但在发送通知之前立即关闭的不幸时间而丢失通知。它wouldn't在发送通知时出现问题的情况下提供帮助,例如您的邮件服务器已关闭。此时,用户已被告知电子邮件正在发送中,然后您才能真正保证......只是需要考虑的事情。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ThreadPool.QueueUserWorkItem 的 .NET Core 替代品 的相关文章

随机推荐