2014-05-15 16 views
0

C#的新手 - 我已經將來自示例項目的代碼部分拼湊在一起,這些示例項目是我在線發現的,與我正在嘗試完成的項目相近 - 並且它拒絕行爲同樣的方式。到目前爲止,我已經學到了很多東西,並做了很多調整,但這件作品繼續避開我,並且我找不到任何相同的在線內容。在示例程序中,backgroundWorker.RunWorkerAsync();跳到程序的下一部分。在我的代碼中,它不會。我在許多不同的地方放置了休息點,並且它總是停下來,並且似乎在RunWorkerAsync()中掛起。我認爲問題的一部分是,示例程序的原作者使用後臺工作者的方式與我在網上看到的大多數示例並不一致,但它在示例程序中起作用,當我在其上運行它時擁有。我錯過了什麼?RunWorkerAsync()

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using System.IO; 
using System.Text.RegularExpressions; 

namespace DIPUtil 
{ 
public partial class DIPform : Form 
{ 
    #region Fields 
    private string outputDirectory; 
    protected string findWhatString = "BEGIN"; 
    protected string replaceWithText = "FANOODLE"; 


    #endregion 

    #region Background 
    BackgroundWorker worker = new BackgroundWorker(); 

    /// <summary> 
    /// Executes the main find and replace operation. 
    /// </summary> 
    /// <param name="worker">The BackgroundWorker object.</param> 
    /// <returns>The number of files affected by the replace operation.</returns> 
    private int DoFindReplace(BackgroundWorker worker) 
    { 
     //Initialize the affected count variable 
     int filesAffectedCount = 0; 

     //Initialize the counter 
     int counter = 0; 

     //Get all XML files in the directory 
     string[] filesInDirectory = Directory.GetFiles(outputDirectory, "*.txt"); 

     //Initialize total file count 
     int totalFiles = filesInDirectory.GetLength(0); 

     //Analyze each file in the directory 
     foreach (string file in filesInDirectory) 
     { 
      //Perform find and replace operation 
      if (FindAndReplace(file)) 
      { 
       //The file was changed so increment variable 
       filesAffectedCount++; 
      } 

      //Increment the counter 
      counter++; 

      //Report progress 
      worker.ReportProgress((int)((counter/totalFiles) * 100.00)); 
     } 

     //Return the total number of files changed 
     return filesAffectedCount; 
    } 
    #endregion 

    #region FindAndReplace 
    /// <summary> 
    /// Performs the find and replace operation on a file. 
    /// </summary> 
    /// <param name="file">The path of the file to operate on.</param> 
    /// <returns>A value indicating if the file has changed.</returns> 
    private bool FindAndReplace(string file) 
    { 
     //holds the content of the file 
     string content = string.Empty; 

     //Create a new object to read a file 
     using (StreamReader sr = new StreamReader(file)) 
     { 
      //Read the file into the string variable. 
      content = sr.ReadToEnd(); 
     } 

     //Get search text 
     string searchText = GetSearchText(findWhatString); 

     //Look for a match 
     if (Regex.IsMatch(content, searchText)) 
     { 
      //Replace the text 
      string newText = Regex.Replace(content, searchText, replaceWithText); 

      //Create a new object to write a file 
      using (StreamWriter sw = new StreamWriter(file)) 
      { 
       //Write the updated file 
       sw.Write(newText); 
      } 

      //A match was found and replaced 
      return true; 
     } 

     //No match found and replaced 
     return false; 
    } 
    #endregion 

    #region Various 
    /// <summary> 
    /// Gets the text to find based on the selected options. 
    /// </summary> 
    /// <param name="textToFind">The text to find in the file.</param> 
    /// <returns>The text to search for.</returns> 
    private string GetSearchText(string textToFind) 
    { 
     //Copy the text to find into the search text variable 
     //Make the text regex safe 
     string searchText = Regex.Escape(findWhatString); 

     return searchText; 
    } 
    /// <summary> 
    /// Sets the properties of the controls prior to beginning the download. 
    /// </summary> 
    private void InitializeProcess() 
    { 
     //Get sources 
     outputDirectory = txtDirectory.Text; 

     //Set properties for controls affected when replacing 
     statuslabel.Text = "Working..."; 
     progbar.Value = 0; 
     progbar.Visible = true; 
     btnprocess.Enabled = false; 
     btncancel.Enabled = true; 

     //Begin downloading files in background 
     backgroundWorker.RunWorkerAsync(); 
    } 

    /// <summary> 
    /// Sets the properties of the controls after the download has completed. 
    /// </summary> 
    private void DeinitializeProcess() 
    { 
     //Set properties for controls affected when operating 
     statuslabel.Text = "Ready"; 
     progbar.Visible = false; 
     btnprocess.Enabled = true; 
     btncancel.Enabled = false; 
    } 

    /// <summary> 
    /// Displays the directory browser dialog. 
    /// </summary> 
    private void BrowseDirectory() 
    { 
     //Create a new folder browser object 
     FolderBrowserDialog browser = new FolderBrowserDialog(); 

     //Show the dialog 
     if (browser.ShowDialog(this) == DialogResult.OK) 
     { 
      //Set the selected path 
      txtDirectory.Text = browser.SelectedPath; 
     } 
    } 

    /// <summary> 
    /// Validates that the user input is complete. 
    /// </summary> 
    /// <returns>A value indicating if the user input is complete.</returns> 
    private bool InputIsValid() 
    { 
     //Set the error flag to false 
     bool isError = false; 

     //Clear all errors 
     errorProvider.Clear(); 

     //Validate the directory name 
     if (string.IsNullOrEmpty(txtDirectory.Text)) 
     { 
      errorProvider.SetError(txtDirectory, "This is a required field."); 
      isError = true; 
     } 
     else 
     { 
      //check to make sure the directory is valid 
      if (Directory.Exists(txtDirectory.Text) == false) 
      { 
       errorProvider.SetError(txtDirectory, "The selected directory does not exist."); 
       isError = true; 
      } 
     } 

     //Return a value indicating if the input is valid 
     if (isError) 
      return false; 
     else 
      return true; 
    } 

    #endregion 

    #region Events 
    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) 
    { 
     //Create a work object and initialize 
     BackgroundWorker worker = sender as BackgroundWorker; 

     //Run the find and replace operation and store total files affected in the result property 
     e.Result = (int)DoFindReplace(worker); 
    } 

    private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) 
    { 
     //Update the prog bar 
     progbar.Value = e.ProgressPercentage; 
    } 

    private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
    { 
     //The background operation is done 
     DeinitializeProcess(); 

     //Perform final operations 
     if (e.Error != null) 
      MessageBox.Show(this, e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     else if (e.Cancelled) 
      MessageBox.Show(this, "The operation was ended by the user.", "Cancelled.", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     else 
      MessageBox.Show(this, string.Format("{0} files were updated by the operation.", e.Result.ToString()), "Replace Complete", MessageBoxButtons.OK, MessageBoxIcon.Information); 

    } 
    public DIPform() 
    { 
     InitializeComponent(); 
    } 

    private void DIPform_Load(object sender, EventArgs e) 
    { 

    } 

    private void btnprocess_Click(object sender, EventArgs e) 
    { 
     //Verify input is ok 
     if (InputIsValid()) 
      InitializeProcess(); 
    } 

    private void btncancel_Click(object sender, EventArgs e) 
    { 

    } 

    //private void linkbrowse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) 
    // { 
     //Select a directory to output files 
    // BrowseDirectory(); 
    //} 
    private void linkbrowse_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e) 
    { 
     //Select a directory to output files 
     BrowseDirectory(); 
    } 
    #endregion 



} 
} 
+0

您是否已將BackgroundWorker通過窗體設計器放置到窗體上?因爲你應該......如果你沒有,請回過頭來通過設計師添加它。 –

+1

你在哪裏設置'backgroundWorker.DoWork'事件? – Ric

+0

是的,它被添加到窗體設計器中的窗體中。 – hispeedzintarwebz

回答

1

當你調用RunWorkerAsync(),事件DoWork提高。發生這種情況時,已添加到這一事件的方法將被執行:

backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {/...}

檢查你的設計師,看看它是否正確接線。

在這裏看到更多的信息:

BackGround Worker Class.

+0

backgroundworker.DoWork + = new ..... line - 是否在InitializeComponent()下的公共DIPform()部分進行?我在例子中看到它,但它沒有解決我的問題,也沒有在原始示例代碼中。 – hispeedzintarwebz

+0

直接位於構造函數中的'InitializeComponent();'的下方。 – Ric

+0

添加了這個 - 以及查看上面的鏈接(這在某種程度上我從未在所有關於BackgroundWorker的MSDN搜索中找到),並將表單上的元素「綁定」到代碼中的事件。從來不知道屬性瀏覽器中的閃電。非常感謝你和@MichaelPerrenoud。 – hispeedzintarwebz

-3

你有什麼期望?如果您通過設計器將您的後臺工作人員放置在窗體上,並連接事件處理程序,然後通過創建一個新的引用(如您所做的那樣)手動分配一個新引用,則變量內的引用值將更改,現在是變量中的另一個引用,事件監聽者以前將其作爲參考。您不需要創建新的BackroundWorker,如果您將其拖放到設計器的表單上。如果你通過代碼實現了某些功能,那麼你需要實例化,手動添加監聽器等等......這兩種方式都是如何處理這個問題的部分排他性方式,只有當你有一個清晰的視圖時,才能混合它們。

相關問題