我正在开发.net核心Web应用程序,并且遇到了一个问题,即我的Usermanager被处置,导致错误。
public async void DeleteInactiveUserData()
{
var dayAgo = DateTimeOffset.UtcNow.AddDays(-1);
var inactiveGuests = _userManager.Users.Where(u => u.Guest && u.LastLoginDate < dayAgo);
var yearAgo = DateTimeOffset.UtcNow.AddYears(-1);
var inactiveUsers = _userManager.Users.Where(u => !u.Guest && u.LastLoginDate < yearAgo);
var toBeDeletedUsers = inactiveGuests.Concat(inactiveUsers).ToList();
for (int i = toBeDeletedUsers.Count() - 1; i >= 0; i--)
{
var user = toBeDeletedUsers[i];
_logger.LogInformation("Deleting user " + user.UserName + " for inactivity.");
await _userManager.DeleteAsync(user); // Usermanager is disposed here
}
}
如何在使用等待时停止处理服务?
答案 0 :(得分:0)
正如评论所建议的那样,我没有提供足够的细节,但在扩展问题时遇到了答案。我学到的是这样:
始终返回异步任务,而不是异步void
Cannot access a disposed object. A common cause of this error is disposing a context
在关闭范围之前等待任务:
using (var scope = _serviceScopeFactory.CreateScope())
{
var accountServive = scope.ServiceProvider.GetService<IAccountService>();
await accountServive.DeleteInactiveUserData();
}
如果不等待任务,该功能将继续,作用域将关闭并且您的服务将被处置。要了解异步并等待,请转到此处:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/