【问题标题】:Background worker and Functions后台工作者和函数
【发布时间】:2013-12-15 11:13:57
【问题描述】:

我有一个后台工作人员。它工作得很好但是我想把它用完的代码移出 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;
        }
    }

【问题讨论】:

    标签: wpf backgroundworker


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多