C# 运行 加载表单时的 WMI 查询

C# running WMI query while loading form

我有一个 C#/Winforms 程序需要在初始表单上列出计算机的网络适配器,因此这是我的函数的简化版本,用于汇总该列表:

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

为了简单起见,我没有包含 try/catch 或任何其他内容,但此函数应该编译并 运行。此函数由 Form1_Load() 调用。问题是,这会导致相当长的延迟加载表单,并且无法使用正常的 async/await 功能。

我在 运行ning ManagementObjectSearcher 上异步找到了这篇 MSDN 文章:https://msdn.microsoft.com/en-us/library/cc143292.aspx 我想在后台启动 LoadNicList(),而表单以 "Loading" 消息开头组合框,然后在列表准备就绪后填充列表,但我不知道如何操作。可行吗?

尝试使用这个而不只是 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);