Bernhard
Bernhard

Reputation: 195

c# GroupPrincipal.GetMembers Performance Problems

in our enviroment there are two AD Domains: DomainA and DomainB. There is a one way trust from DomainB to DomainA.

We are using the following code to list all Users of an AD Group from DomainA from a Server in Domain (we are using a User from DomainA for the Principal Context):

using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DomainA", "DomainA\\user", "pwd");
{
    using (GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, "DomainA\\DomainGroup"))
    { 
        var members = grp.GetMembers(true);

        foreach (Principal p in members)
        {
            string email = string.Empty;
            UserPrincipal u = p as UserPrincipal;

            if (u != null)
            {
                email = u.EmailAddress;
            }

            if (!String.IsNullOrEmpty(email) && !users.Contains(email))
            {
                users.Add(email);
            }
        }
    }
}

This code is executed within an IIS Webservice.

The code works quite well after a restart of the server in DomainB, but after a couple of tries the code gets extrem slow. There are about 700 Members in the AD Group. The code takes about 5-10 seconds after the restart, after some time the code takes about 2-3 Minutes!

Can anyone help me with this issue?

Best Regards Bernhard

Upvotes: 2

Views: 1266

Answers (1)

Baldrick
Baldrick

Reputation: 11840

Try with

using (var members = grp.GetMembers(true))
{   }

The GetMembers call returns an IDisposable, and you're not it cleaning up.

See MS documentation here.

public class PrincipalSearchResult : IEnumerable, IEnumerable, IDisposable

Upvotes: 4

Related Questions