我正在尝试编写一个实用程序,以查看自从我在数据库中存储的日期以来,用户是否已登录到Windows。
private void bwFindDates_DoWork(object sender, DoWorkEventArgs e)
{
UserPrincipal u = new UserPrincipal(context);
u.SamAccountName = "WebLogin*";
PrincipalSearcher ps = new PrincipalSearcher(u);
var result = ps.FindAll();
foreach (WebAccess.WebLoginUsersRow usr in webAccess.WebLoginUsers)
{
UserPrincipal b = (UserPrincipal)result.
Single((a) => a.SamAccountName == usr.WEBUSER);
if (b.LastLogon.HasValue)
{
if (b.LastLogon.Value < usr.MODIFYDATE)
usr.LastLogin = "Never";
else
usr.LastLogin = b.LastLogon.Value.ToShortDateString();
}
else
{
usr.LastLogin = "Never";
}
}
}
然而,性能非常慢。我从中获取的用户列表大约有150个Windows用户,因此当我遇到这行代码时
UserPrincipal b = (UserPrincipal)result.Single((a) => a.SamAccountName == usr.CONVUSER);
每个用户需要10到15秒才能完成(通过逐步执行,我可以看到它在运行 a.SamAccountName == usr.CONVUSE
步骤以获取每个人,所以最坏情况下运行O(n ^ 2)次)。有什么建议可以提高效率吗?