简体   繁体   English

异步远程WMI调用C#

[英]Asynchronous Remote WMI Calls C#

I'm really struggling to get WMI data from a remote host in an asynchronous way. 我真的很难以异步方式从远程主机获取WMI数据。 After a lot of research, I can't find any clear examples, Microsoft's documentation only has VB and C++ code and there are even articles explaining why it's a bad idea. 经过大量的研究,我找不到任何明确的例子,微软的文档只有VB和C ++代码,甚至有文章解释为什么这是一个坏主意。 I've come from PowerShell, with that I would just create a new runspace to get the information. 我来自PowerShell,我只想创建一个新的运行空间来获取信息。

I currently have a WPF window that I want to remain responsive whilst querying the information before updating the window. 我目前有一个WPF窗口,我希望在更新窗口之前查询信息时保持响应。 I've currently only managed to use synchronous calls using CimSession.Create and QueryInstance. 我目前只使用CimSession.Create和QueryInstance设法使用同步调用。

I would really appreciate some help with this :) 我真的很感激这个帮助:)

You can use ORMi async methods to do async WMI work. 您可以使用ORMi异步方法执行异步WMI工作。 For example: 例如:

WMIHelper helper = new WMIHelper("root\\CimV2");
List<Processor> processors = await helper.QueryAsync<Processor>().ToList();

After proposing the same question to the MSDN forums, I got the correct answer and thought I would share it here as well :) I have put comments into the code to explain what is happening: 在向MSDN论坛提出同样的问题后,我得到了正确的答案,并认为我也会在这里分享:)我已经在代码中添加了注释来解释发生了什么:

//Used to define what is returned in the async results
public static CimAsyncMultipleResults<CimInstance> GetValues(CimSession _session)
{
    return _session.QueryInstancesAsync(@"root\cimv2", "WQL", "SELECT Username FROM Win32_ComputerSystem");
}

//This watches the async progress
class CimInstanceWatcher : IObserver<CimInstance>
{
    public void OnCompleted()
    {
        Console.WriteLine("Done");
    }

    public void OnError(Exception e)
    {
        Console.WriteLine("Error: " + e.Message);
    }

    public void OnNext (CimInstance value)
    {
        Console.WriteLine("Value: " + value);
    }
}

private static void Main()
{
    //Leaving cimsession creation as sync because is happens "instantly"
    CimSession Session = CimSession.Create("PC-NAME");
    //Creating a new watcher object
    var instanceObject = new CimInstanceWatcher();
    //Subscribing the watcher object to the async call
    GetValues(Session).Subscribe(instanceObject);
    Console.ReadLine();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM