ozzie286
ozzie286

Reputation: 15

C# running WMI query while loading form

I've got a C#/Winforms program that needs to list the computer's network adapters on the initial form, so this is a simplified version of my function to put together that list:

void LoadNicList() 
{
    ManagementObjectSearcher mos = new ManagementObjectSearcher(@"SELECT * 
                                         FROM   Win32_NetworkAdapter 
                                         WHERE  Manufacturer != 'Microsoft'
                                         AND NOT ProductName LIKE '%Wireless%'
                                         AND NOT ProductName LIKE '%Wifi%'
                                         AND NOT ProductName LIKE '%Wi-Fi%'
                                         AND NOT PNPDeviceID LIKE 'ROOT\\%'");
    foreach (ManagementObject mo in mos.Get())
    {
        if (mo["MACAddress"] != null)
        {
            comboBox1.Items.Add(mo["name"].ToString());
        }
    }
}

I haven't included the try/catch or any of the other stuff that goes on just to keep it simple, but this function should compile and run. This function is called by Form1_Load(). The problem is, this can cause quite a long delay loading the form, and the normal async/await functions can't be used.

I found this MSDN article on running ManagementObjectSearcher asynchronously: https://msdn.microsoft.com/en-us/library/cc143292.aspx I'd like to start LoadNicList() in the background while the form starts with a "Loading" message in the combobox, and then populate the list once it's ready, but I can't figure out how. Is that doable?

Upvotes: 0

Views: 381

Answers (1)

nGX
nGX

Reputation: 1068

Try using this instead of just LoadNicList()

    //create cancellation token for future use
            CancellationToken cancellationToken = new CancellationToken();

//uischeduler is used to update the UI using the main thread
            TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
            Task.Factory.StartNew(() =>
                            {
                                LoadNicList();
                            }, cancellationToken, TaskCreationOptions.None, uiScheduler);

Upvotes: 1

Related Questions