背景工作者和功能

时间:2013-12-14 19:53:34

标签: wpf backgroundworker

我有一名背景工作者。它的工作完全没问题,但我想移动它运行的DoWork代码是否可能?

    void NewWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        List<string> ReturnResults = new List<string>();
        BackgroundWorker worker = sender as BackgroundWorker;

                ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select StatusCode from Win32_PingStatus where address = 'Metabox-PC'");
                ManagementObjectCollection objCollection = searcher.Get();
                foreach (ManagementObject Results in objCollection)
                {
                    ReturnResults.Add(Results["StatusCode"].ToString());
                }
                e.Result = ReturnResults;
                // Perform a time consuming operation and report progress.
                System.Threading.Thread.Sleep(1);
    }

所以在实际查询WMI的地方,我希望能够在我喜欢的地方添加任何计算机。

这可能吗?

    public void StartBackgroundWorker()
    {

        BackgroundWorker NewWorker = new BackgroundWorker();
        NewWorker.DoWork += new DoWorkEventHandler(NewWorker_DoWork);
        NewWorker.ProgressChanged += new ProgressChangedEventHandler(NewWorker_ProgressChanged);
        NewWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(NewWorker_RunWorkerCompleted);
        NewWorker.WorkerReportsProgress = true;

        NewWorker.RunWorkerAsync();
    }
    void NewWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        List<string> ReturnResults = new List<string>();
        BackgroundWorker worker = sender as BackgroundWorker;

                BackgroundWorkerOperations NewOperation = new BackgroundWorkerOperations();
                NewOperation.Operations(GlobalComputerName);

                e.Result = ReturnResults;
                // Perform a time consuming operation and report progress.
                System.Threading.Thread.Sleep(1);
    }

    public class BackgroundWorkerOperations
    {
        public Operations(string ComputerNames)
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select StatusCode from Win32_PingStatus where address = '" + ComputerNames + '");
            ManagementObjectCollection objCollection = searcher.Get();
            foreach (ManagementObject Results in objCollection)
            {
                ReturnResults.Add(Results["StatusCode"].ToString());
            }
            e.Result = ReturnResults;
        }
    }

1 个答案:

答案 0 :(得分:0)

是的,有可能。将DoWork的一部分移动到其他功能并在DoWork中调用该功能,您的程序仍将在DoWork中执行相同的操作。无论如何,在编码中我们通常无法确定,直到我们尝试。所以,试试你的第二个代码,看起来很好。