WMI连接到ManagementScope
问题描述:
我使用C#和WMI进行一些测试WMI连接到ManagementScope
我想知道连接到ManagementScope的目的是什么? 在我的测试中,不管我是否使用“scope.Connect()”,结果都是一样的。
ManagementScope scope = new ManagementScope("\\\\" + sServer +"\\root\\CIMV2", oConn);
// scope.Connect() ; When should I use this? Code works without it....
// if (scope.IsConnected)
// Console.WriteLine("Scope connected");
ObjectQuery query = new ObjectQuery("SELECT FreeSpace FROM Win32_LogicalDisk where DeviceID = 'C:'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
freeSpace = (ulong)m.GetPropertyValue("FreeSpace");
Console.WriteLine (freeSpace)
}
答
从.NET源代码:
ManagementObjectSearcher.Get()
的方法调用方法Initialize
:
public void Get(ManagementOperationObserver watcher)
{
if (null == watcher)
throw new ArgumentNullException ("watcher");
Initialize();
// ... more code
}
和Initialize()
方法实际上证实如果范围已经正确初始化,并连接到如果它没有:
private void Initialize()
{
//If the query is not set yet we can't do it
if (null == query)
throw new InvalidOperationException();
//If we're not connected yet, this is the time to do it...
lock (this)
{
if (null == scope)
scope = ManagementScope._Clone(null);
}
lock (scope)
{
if (!scope.IsConnected)
scope.Initialize();
}
}
因此,如果您使用ManagementSearcherObject
,则不必自己拨打Connect()
方法。但是,您仍然可以从另一个对象访问搜索者,然后您需要验证自己是否连接到了管理范围。
的ManagementScope
类的Connect()
方法但是没有别的,但调用同样的方法Initialize()
:
public void Connect()
{
Initialize();
}