DirectorySearcher FindAll SearchResultCollection计数抛出COMException

时间:2012-04-27 21:45:24

标签: c# .net active-directory directoryservices

我有一些代码在很长一段时间内都能正常运行,以便让某人登录我的应用程序:

private Employee Authenticate(string userName, string password) {
  DirectorySearcher search = new DirectorySearcher(_rootDirectory);
  search.Filter = "(&(objectClass=user)(SAMAccountName=" + userName + "))";
  try {
    SearchResultCollection results = search.FindAll();
    if (0 < results.Count) {
      // the rest of my code
      // that returns an employee
      // if the password matches
    }
  } catch (Exception err) {
    MessageBox.Show(err.Message, "ActiveDir.cs ADWrapper::AuthenticateUser Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  }
  return null;
}

最近,一旦我测试results.Count值(COMException不为空),代码就会抛出SearchResultCollection

Microsoft的文档并未指出Count应该抛出任何类型的例外。

在调试我的代码时,我可以将断点放在上面的条件上,将鼠标悬停在它上面,然后看到异常存在。

screenshot of exception

如果我使用 F10 让调试器将我带到catch条件或在断点上等待几秒钟,results.Count变量变为有效且包含整数值。

我猜测FindAll方法正在线程中执行,而且我在线程完成之前检查结果。

有没有办法告诉FindAll()何时完成,或者我刚刚发现因 Active Directory 更新而发生的某种新错误?

2 个答案:

答案 0 :(得分:1)

这是一个调试器工件。调试表达式在进程内的辅助线程上执行。事实上,它与执行代码的不同的线程可能会产生副作用。例如,明显的情况是在其getter中使用 lock 的属性。

不那么明显的是任何与COM相关的东西,比如Active Directory。 COM为非线程安全的COM服务器实现线程安全性。这在调试器线程上无法正常工作,创建服务器的线程被冻结。还有其他任何可能出错的地方,比如没有代理/存根来编组调用等等。

你没有真正的问题。

答案 1 :(得分:0)

我发现OP的确切行为。我的问题是我的过滤器有一个错误 - 当发生这种情况时我没有得到FindAll()抛出的错误但是然后尝试访问.Count在调试器中给出错误......几秒钟后.Count返回零。