WMI 连接到 ManagementScope

WMI connect to ManagementScope

我用 C# 和 WMI 做了一些测试

我想知道连接到 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 class 的 Connect() 方法只是调用相同的 Initialize() 方法:

    public void Connect ()
    {
        Initialize ();
    }

可以看到here and here