2

我对这段代码有问题......显然,它可以工作,但对我来说太慢了,有人有什么想法吗?当我尝试访问以下内容时它会变慢

Dim u As UserPrincipal = UserPrincipal.FindByIdentity(ctx, p.SamAccountName)

同样,以下代码可以正常工作,但速度很慢。如果我取出上面的一段代码并p.SamAccountName在 1 秒内完成搜索,那么我确定我做错了什么。

Dim sw As New Stopwatch

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    sw.Start()

    DataGridView1.ColumnCount = 3
    DataGridView1.Columns(0).Name = "Account Name"
    DataGridView1.Columns(1).Name = "First Name"
    DataGridView1.Columns(2).Name = "Last Name"

    Dim ctx = New PrincipalContext(ContextType.Domain, "JOI", DomainName)
    Dim userPrin As New UserPrincipal(ctx)
    userPrin.Name = "*"
    Dim searcher = New System.DirectoryServices.AccountManagement.PrincipalSearcher()
    searcher.QueryFilter = userPrin
    Dim results = searcher.FindAll()

    For Each p As Principal In results
        Dim u As UserPrincipal = UserPrincipal.FindByIdentity(ctx, p.SamAccountName)
        Dim row As String() = New String() {u.SamAccountName, u.GivenName, u.Surname}
        DataGridView1.Rows.Add(row)
    Next

    sw.Stop()
    MessageBox.Show("Finished in :" & sw.Elapsed.Duration.Seconds & " seconds")

End Sub

Private Shared Function DomainName() As String

    Dim objRootDSE As New DirectoryEntry("LDAP://RootDSE")
    DomainName = objRootDSE.Properties("defaultNamingContext")(0)

End Function
4

1 回答 1

1

您已经可以访问UserPrincipal搜索结果中的 ,然后您正在对结果中的每个项目执行另一个新搜索。这正是减慢您的功能的原因。

我通常过滤过滤器(LINQ)并且只获取UserPrincipal类型的结果项。这样,它只是一次通过搜索

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    sw.Start()

    DataGridView1.ColumnCount = 3
    DataGridView1.Columns(0).Name = "Account Name"
    DataGridView1.Columns(1).Name = "First Name"
    DataGridView1.Columns(2).Name = "Last Name"

    Using context As PrincipalContext = New PrincipalContext(ContextType.Domain, "JOI", DomainName)
        Using userPrin As UserPrincipal = New UserPrincipal(context)
            userPrin.Name = "*"
            Using searcher As PrincipalSearcher = New PrincipalSearcher(userPrin)

                Dim results = searcher _
                    .FindAll() _
                    .OfType(Of UserPrincipal)()

                For Each p As UserPrincipal In results
                    Dim row As String() = New String() {p.SamAccountName, p.GivenName, p.Surname}
                    DataGridView1.Rows.Add(row)
                Next
            End Using
        End Using
    End Using

    sw.Stop()
    MessageBox.Show("Finished in :" & sw.Elapsed.Duration.Seconds & " seconds")

End Sub
于 2016-06-11T02:12:35.173 回答