1

我创建了一个函数,可以一次将一个用户添加到特定组(管理员等),但响应 GroupPrinciple(5-10 秒)和 group.members.add(5-10 秒)调用似乎需要很长时间并减慢我的应用程序,响应需要将近 15-20 秒,有没有更快的方法来做到这一点?

private static void Add()
{
 var userContext = new PrincipalContext(ContextType.Domain);
 var user = new UserPrincipal(userContext);
 user.SamAccountName = "c1111111";
 var searcher = new PrincipalSearcher(user);
 user = searcher.FindOne() as UserPrincipal;

var machineContext = new PrincipalContext(ContextType.Machine, "ABCDEFGHI1",
   null, ContextOptions.Negotiate, "c123789", "test123");
var group = GroupPrincipal.FindByIdentity(machineContext,"Administrators"); 

group.Members.Add(user); 

Console.WriteLine("saving group");
group.Save();

}
4

2 回答 2

0

我自己也遇到过这个问题,因为您每次都使用同一个组,看看您是否可以从添加用户中重构出组的发现并一次添加多个用户。

private static void Add(IEnumerable<UserPrincipal> users)
{
    var machineContext = new PrincipalContext(ContextType.Machine, "ABCDEFGHI1",
       null, ContextOptions.Negotiate, "c123789", "test123");
    var group = GroupPrincipal.FindByIdentity(machineContext,"Administrators"); 
    foreach(var user in users)
    {
        group.Members.Add(user); 
    }
    Console.WriteLine("saving group");
    group.Save();
}

或者另一种选择是先找到该组,然后将其缓存。使用Task.Run使这非常容易,只需在静态构造函数中启动任务,然后在 Add 函数中获取结果。.Result将阻塞直到任务完成,然后将立即执行。重要说明,GroupPrincipal不是线程安全的,因此您需要锁定对类的修改。

static YourClassName()
{
    _administratorsGroup = Task.Run(() =>
    {
        var machineContext = new PrincipalContext(ContextType.Machine, "ABCDEFGHI1",
           null, ContextOptions.Negotiate, "c123789", "test123");
        return GroupPrincipal.FindByIdentity(machineContext,"Administrators"); 
    });
}

private static Task<GroupPrincipal> _administratorsGroup;

private static void Add(UserPrincipal user)
{
    group = _administratorsGroup.Result;
    lock(group)
    {
        group.Members.Add(user); 

        Console.WriteLine("saving group");
        group.Save();
    }
}

如果这将在 UI 线程上替换为_administratorsGroup.Resultawait _administratorsGroup它也具有相同的等待行为,但不会锁定您的 UI。

于 2015-06-12T15:38:21.387 回答
0

FindAll()对于 ContextType.Machine 来说要快得多。然后只需通过可用输入过滤结果:NameUserPrincipalName或.SAMAccountNameSid.Value

Linq 变体,未经 ContextType.Domain 测试:

PrincipalContext principalContext = new PrincipalContext(ContextType.Machine);

// user (input: userSID)
PrincipalSearcher userPrincipalSearcher = new PrincipalSearcher(new UserPrincipal(principalContext));
UserPrincipal userPrincipal = userPrincipalSearcher.FindAll().FirstOrDefault(x => (x is UserPrincipal) && x.Sid.Value == userSID) as UserPrincipal;

// group (input: groupSID)
PrincipalSearcher groupPrincipalSearcher = new PrincipalSearcher(new GroupPrincipal(principalContext));
GroupPrincipal groupPrincipal = groupPrincipalSearcher.FindAll().FirstOrDefault(x => (x is GroupPrincipal) && x.Sid.Value == groupSID) as GroupPrincipal;
于 2022-03-04T17:47:10.820 回答