0

I'm developing a .net core web app and I am running into a problem where my Usermanager is being disposed, resulting in an error.

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
    }
}

How do I stop service from being disposed of while using the await?

Keyur Ramoliya
  • 1,900
  • 2
  • 16
  • 17
Frank
  • 3
  • 3
  • Please add some details. Post an [mcve] or at least explain why you think it gets disposed. We don't know *anything* about your code. What is `_userManager`? Where is it created? Is your function itself not awaited? – nvoigt Aug 07 '20 at 05:41
  • Also, you say you get an error but you haven't given us the *error message*. – Damien_The_Unbeliever Aug 07 '20 at 07:07
  • Thank you for responding. While expanding my question with a reproducible example I ran into the answer. I'm sorry for wasting your time, I will update the question/answer. – Frank Aug 08 '20 at 04:25

1 Answers1

0

As the comments suggest I did not supply enough details but I ran into the answer while expanding the question. What I learned is this:

Always return async Task instead of async void

Cannot access a disposed object. A common cause of this error is disposing a context

Await your task before closing the scope:

using (var scope = _serviceScopeFactory.CreateScope())
        {
            var accountServive = scope.ServiceProvider.GetService<IAccountService>();
            await accountServive.DeleteInactiveUserData();
        }

If you do not await your task the function will continue, the scope will close and your services will be disposed. To learn about async and await go here:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/

Frank
  • 3
  • 3