Bulk User Creation in OwinContext (Performance)

662 views Asked by At

I am uploading a excel file containing all required users into my website using ASP.NET Identity and OwinContext and EF 6. My code looks like below:

foreach (var bulkUserDetail in bulkUser.BulkUserDetails)
{

        var userManager = owinContext.GetUserManager<ApplicationUserManager>();

        var userProfile = new UserProfile();

        userProfile.Username = bulkUserDetail.Username;


        AspNetUser newUser = new AspNetUser
        {
            UserName = userProfile.Username,
            Email = bulkUserDetail.Email,
            LastPasswordChangedDate = null,
        };

        var creationResult = userManager.Create(newUser);

        if (creationResult.Succeeded)
        {

            string token = userManager.GeneratePasswordResetToken(newUser.Id);

        }

}

The issue is that the performance of following two lines is pretty disappointing

userManager.Create(newUser) -- (900 milliseconds)
userManager.GeneratePasswordResetToken(newUser.Id)      --(1800 milliseconds)

In large quantity, i.e 2000 users, the performance become a serious issue. Is there better a practice to speed up this process? I am open to suggestions but I have to keep the OwinContext library.

Thanks in advance

1

There are 1 answers

1
Mike Norgate On

You could try doing the user creation inside a parallel for which might speed up the overall time, however there is an issue with this:

  • The call to Create and GeneratePasswordResetToken are slow because they call the database
  • Doing the work in parallel would increase the number of concurrent calls to the database potentially slowing it down even more, this really depends on how good the hardware hosting your database is.

    var userManager = owinContext.GetUserManager<ApplicationUserManager>();
    
    Parallel.ForEach (bulkUser.BulkUserDetails, bulkUserDetail => 
    {       
        //Do you really need to make this userProfile as its not used
        var userProfile = new UserProfile();
    
        userProfile.Username = bulkUserDetail.Username;
    
        AspNetUser newUser = new AspNetUser
        {
            UserName = userProfile.Username,
            Email = bulkUserDetail.Email,
            LastPasswordChangedDate = null,
        };
    
        var creationResult = userManager.Create(newUser);
    
        if (creationResult.Succeeded)
        {
    
            string token = userManager.GeneratePasswordResetToken(newUser.Id);
    
        }
    })