我也有一个使用插件和应用程序域的长期运行服务,由于使用directoryservices而导致内存泄漏。请注意,我正在使用system.directoryservices.accountmanagement,但我理解它使用相同的底层ADSI API,因此容易出现相同的内存泄漏问题。
我查看了所有CLR内存计数器,发现内存并没有泄漏,在强制GC或卸载应用程序域时,内存都会被释放。泄漏是在私有字节中不断增长。我在这里搜索过一些与ADSI API相关的内存泄漏问题,但它们似乎表明仅迭代directorysearcher即可解决问题。但是,如下所示的代码中,我正在使用foreach块进行迭代,但内存仍在泄漏。有什么建议吗?以下是我的方法:
我对foreach循环做了以下修改,效果更好了,但私有字节仍然增长,并且永远不会被回收。
我查看了所有CLR内存计数器,发现内存并没有泄漏,在强制GC或卸载应用程序域时,内存都会被释放。泄漏是在私有字节中不断增长。我在这里搜索过一些与ADSI API相关的内存泄漏问题,但它们似乎表明仅迭代directorysearcher即可解决问题。但是,如下所示的代码中,我正在使用foreach块进行迭代,但内存仍在泄漏。有什么建议吗?以下是我的方法:
public override void JustGronkIT()
{
using (log4net.ThreadContext.Stacks["NDC"].Push(GetMyMethodName()))
{
Log.Info("Inside " + GetMyMethodName() + " Method.");
System.Configuration.AppSettingsReader reader = new System.Configuration.AppSettingsReader();
//PrincipalContext AD = null;
using (PrincipalContext AD = new PrincipalContext(ContextType.Domain, (string)reader.GetValue("Domain", typeof(string))))
{
UserPrincipal u = new UserPrincipal(AD);
u.Enabled = true;
//u.Surname = "ju*";
using (PrincipalSearcher ps = new PrincipalSearcher(u))
{
myADUsers = new ADDataSet();
myADUsers.ADUsers.MinimumCapacity = 60000;
myADUsers.ADUsers.CaseSensitive = false;
foreach (UserPrincipal result in ps.FindAll())
{
myADUsers.ADUsers.AddADUsersRow(result.SamAccountName, result.GivenName, result.MiddleName, result.Surname, result.EmailAddress, result.VoiceTelephoneNumber,
result.UserPrincipalName, result.DistinguishedName, result.Description);
}
ps.Dispose();
}
Log.Info("Number of users: " + myADUsers.ADUsers.Count);
AD.Dispose();
u.Dispose();
}//using AD
}//Using log4net
}//JustGronkIT
我对foreach循环做了以下修改,效果更好了,但私有字节仍然增长,并且永远不会被回收。
foreach (UserPrincipal result in ps.FindAll())
{
using (result)
{
try
{
myADUsers.ADUsers.AddADUsersRow(result.SamAccountName, result.GivenName, result.MiddleName, result.Surname, result.EmailAddress, result.VoiceTelephoneNumber, result.UserPrincipalName, result.DistinguishedName, result.Description);
result.Dispose();
}
catch
{
result.Dispose();
}
}
}//foreach