2013-12-14 190 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中執行相同的操作。無論如何,在編碼中,我們通常無法確定,直到我們嘗試。所以只需要嘗試一下你的第二個代碼,它看起來很好。