2010-12-21 68 views
0

在c#中創建一個基於線程的應用程序,它從用戶選擇的計算機(實際上是遠程計算機)讀取一個文本文件。如果用戶對原始文件進行了任何更改,則該應用程序應該顯示修改後的文件(整體)。在C#中的自動文件更新?

它的成功但是,我正在使用的線程不知道如何以及在哪裏放置它連續從背景中讀取原始文件。我的應用程序獲取掛起與此代碼

public partial class FormFileUpdate : Form 
{ 
    // This delegate enables asynchronous calls for setting the text property on a richTextBox control. 
    delegate void UpdateTextCallback(object text); 

    // This thread is used to demonstrate both thread-safe and unsafe ways to call a Windows Forms control. 
    private Thread autoReadThread = null; 


    public FormFileUpdate() 
    { 
     InitializeComponent(); 

     //Creating Thread 
     this.autoReadThread = new Thread(new ParameterizedThreadStart(UpdateText)); 
    }  

    private void openToolStripButton_Click(object sender, EventArgs e) 
    { 
     OpenFileDialog fileOpen = new OpenFileDialog(); 
     fileOpen.Title = "Select a text document"; 
     fileOpen.Filter = @"Text File|*.txt|Word Document|*.rtf|MS office Documnet|*.doc|See All files|*.*"; 
     fileOpen.FilterIndex = 1; 
     fileOpen.RestoreDirectory = true; 
     fileOpen.Multiselect = false; 
     if (fileOpen.ShowDialog() == DialogResult.OK) 
     {   
      //Created Thread will start here 
      this.autoReadThread.Start(fileOpen.FileName); 
     } 
    } 

    private void UpdateText(object fileName) 
    {  
     StreamReader readerStream = null; 
     while(true) 
     { 
      if (this.richTextBox1.InvokeRequired) 
      { 
       UpdateTextCallback back = new UpdateTextCallback(UpdateText); 
       this.Invoke(back, new object[] { fileName }); 
      } 
      else 
      {  
       try 
       { 
        string fileToUpdate = (string)fileName; 
        readerStream = new StreamReader(fileToUpdate); 
        richTextBox1.Text = readerStream.ReadToEnd(); 
       }  
       catch (Exception ex) { MessageBox.Show(ex.Message); }  
       finally 
       { 
        if (readerStream != null) 
        { 
         readerStream.Close(); 
         Thread.Sleep(100); 
        } 
       } 
      } 
     } 
    } 
} 

回答

0

附加說明什麼伊泰寫道:

要調用從GUI線程Thread.Sleep!爲什麼在關閉文件後甚至需要延遲?如果您出於某種原因確實需要此延遲(例如,爲了避免頻繁讀取文件),請勿將此延遲放在GUI線程上,因爲這會使您的應用程序無響應。

編輯:回答你的問題在評論

一個可能的清潔方法是設置一個Timer這將調用每x秒BackgroundWorker

BackgroundWorker可以很容易地在後臺線程中運行代碼,並且在工作完成時在GUI線程上運行回調。而且您不必直接處理InvokeInvokeRequired。另外,我將創建一個包裝BackgroundWorker的類,以便輕鬆地從讀取文件的操作(在後臺線程中)向更新UI(在GUI線程中)傳遞數據。

+0

所以我應該創建另一個線程處理這個類? – PawanS 2010-12-21 12:31:12

1
  1. 您正在從GUI線程這是一個耗時的動作讀取文件。只有GUI更新應該在開始調用時完成。
  2. 儘量不要在while(true)時使用,只能在文件更改時使用FileSystemWatcher類來更新顯示(請參閱here)。
+0

那麼我應該在哪裏創建線程文件讀取?如果我使用FileSystemWatch,我不認爲我需要實現線程 – PawanS 2010-12-21 12:06:36

+1

使用'FileSystemWatcher'的'Changed'事件來監視文件更改並在事件引發時讀取文件。 – 2010-12-21 12:10:06

+0

@Pawan:確實你不需要線程。 – 2010-12-21 12:27:13