2013-12-14 99 views
0

我有一个后台工作人员。它的工作非常好,但是我想移动它运行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); 
    } 

那么,它实际上是querieing 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; 
     } 
    } 

回答

0

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