Performing Asynchronous Remote WMI Calls C#

This was a problem that I was stuck on for a long time. Originally, I made a program in PowerShell that myself and a couple of other people in the company used to query remote computers to retrieve certain information (SN etc). I wanted to make the move to using WPF with C# simply because of its scale, simplicity and flexibility. The things that I saw being done in WPF with C# was beyond anything I could ever dream with PowerShell.

After making the initial leap, I realised that I would how much code I would have to re-write/re-imagine into C# code. Go figure… One thing that I thought would be simple is performing asynchronous operations but this proved to be something I should use with caution. See, I could simply use Task.Run() and perform the actions, but this is like using a sledgehammer to drive in a nail. After a lot of research, I moved from using this approve to using an observer class to watch the operation and using the QueryInstancesAsync method instead of QueryInstances()

This is the code that I ended up with:

//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();
}

This information was provided from Microsofts forums

Enjoy!


Leave a Reply