2010-12-21 66 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