我正在尝试编写一种方法来确定我的域中的哪些计算机是“非活动的”。我能够让它工作的唯一方法是尝试使用以下方法获取计算机的 IP 地址:
Dns.GetHostAddresses( computerName )
如果计算机处于“非活动状态”,它会抛出一个System.Net.Sockets.SocketException
,然后我可以捕获该计算机并将其添加到我的非活动计算机数据表中。这种方法的问题在于它非常缓慢。通过我的 500 台计算机的 Windows 域,大约 300 台计算机处于“非活动状态”,通过这种方法对它们进行排序需要将近 30 分钟。有没有人建议如何判断在我的 Windows 域中注册的计算机是否处于活动状态?
我也尝试通过 ping 我列表中的所有计算机来做到这一点,但是当尝试 ping 一台“非活动”计算机时System.Net.NetworkInformation.PingException
,我必须以相同的方式捕获和处理它。这也给了我近 30 分钟的运行时间来完成这个过程。
这是我的代码。
public void findInactiveComputers( string customerName, string domain )
{
DirectoryEntry entry = new DirectoryEntry( domain );
DirectorySearcher searcher = new DirectorySearcher( entry );
searcher.Filter = ("(objectClass=computer)");
searcher.SizeLimit = int.MaxValue;
searcher.PageSize = int.MaxValue;
// Removes the inactive computers from the DataTable that associated with the customer.
if( _InactiveComputers.Rows.Count != 0 )
{
_InactiveComputers.AsEnumerable().Where( cust => cust["CustomerName"].ToString()
.Equals( customerName, StringComparison.InvariantCultureIgnoreCase ) )
.ToList().ForEach( comp => comp.Delete() );
}
foreach( SearchResult result in searcher.FindAll() )
{
if( result.GetDirectoryEntry().Name.StartsWith( "CN=" ) )
{
string computerName = result.GetDirectoryEntry().Name.Remove( 0, "CN=".Length );
try
{
Dns.GetHostAddresses( computerName );
}
catch( SocketException )
{
DataRow newRow = _InactiveComputers.NewRow();
newRow["ComputerName"] = computerName;
newRow["CustomerName"] = customerName;
_InactiveComputers.Rows.Add( newRow );
}
}
}
Properties.Settings.Default.InvalidComputers = _InactiveComputers;
Properties.Settings.Default.Save();
}
编辑:
我尝试使用多个线程来完成我的任务,但是等待时间仍然很长(我现在正在运行它,它仍然没有完成)。
这是我如何实现它,提高性能的建议?
List<string> inactiveComputerNames = new List<string>();
foreach( SearchResult result in searcher.FindAll() )
{
new Thread( delegate()
{
if( result.GetDirectoryEntry().Name.StartsWith( "CN=" ) )
{
string computerName = result.GetDirectoryEntry().Name.Remove( 0, "CN=".Length );
try
{
Dns.GetHostAddresses( computerName );
}
catch( SocketException )
{
inactiveComputerNames.Add( computerName );
}
}
} ).Start();
}
foreach( string computerName in inactiveComputerNames )
{
DataRow newRow = _InactiveComputers.NewRow();
newRow["ComputerName"] = computerName;
newRow["CustomerName"] = customerName;
_InactiveComputers.Rows.Add( newRow );
}