UserManager线程问题

时间:2018-02-09 04:10:48

标签: c# multithreading asp.net-core asp.net-identity

我正在尝试确保用户只被分配到一个角色。因此,当他们被分配到一个角色时,我试图遍历他们所属的所有其他角色并将其删除。我遇到了线程问题。有时异常表示线程已关闭,有时它会显示“A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe”,有时它会起作用。什么是更好的方法来设置它?

public async void RemoveUserFromOtherSubscriptions(AppUser user, string subscriptionToKeep)
        {
            subscriptionToKeep = subscriptionToKeep.ToLower();
            string subscription;
            foreach (var item in Enum.GetNames(typeof(SubcriptionTypes)))
            {
                //needed to change case to match bc all roles are sent .ToLower() before creation
                subscription = item.ToLower();
                var userIsInRole = await userManager.IsInRoleAsync(user, subscription); 
                if (userIsInRole && (subscription != subscriptionToKeep))
                {
                    //error is here
                    var result = await userManager.RemoveFromRoleAsync(user, subscription);
                }
            }
        }

0 个答案:

没有答案