2014-04-01 63 views
0

我的代碼只是讀取文件,將其拆分爲單詞,並以0.1秒的頻率向文本框中的每個單詞發送。通過文本框顯示文本文件中的文字?

我點擊"button1"來獲取文件和分割。

當我點擊Start_Button後程序卡住了。我在代碼中看不到任何問題。任何人都可以看到它嗎?

我的代碼在這裏;

public partial class Form1 : Form 
    { 
     string text1, WordToShow; 
     string[] WordsOfFile; 
     bool LoopCheck; 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     {   
      OpenFileDialog BrowseFile1 = new OpenFileDialog(); 
      BrowseFile1.Title = "Select a text file"; 
      BrowseFile1.Filter = "Text File |*.txt"; 
      BrowseFile1.FilterIndex = 1; 
      string ContainingFolder = AppDomain.CurrentDomain.BaseDirectory; 
      BrowseFile1.InitialDirectory = @ContainingFolder; 
      //BrowseFile1.InitialDirectory = @"C:\"; 
      BrowseFile1.RestoreDirectory = true; 
      if (BrowseFile1.ShowDialog() == DialogResult.OK) 
      { 
       text1 = System.IO.File.ReadAllText(BrowseFile1.FileName); 
       WordsOfFile = text1.Split(' '); 
       textBox1.Text = text1; 
      } 
     } 

     private void Start_Button_Click(object sender, EventArgs e) 
     { 
      timer1.Interval = 100; 
      timer1.Enabled = true; 
      timer1.Start(); 
      LoopCheck = true; 
      try 
      { 
       while (LoopCheck) 
       { 
        foreach (string word in WordsOfFile) 
        { 
         WordToShow = word; 
         Thread.Sleep(1000); 
        } 
       } 
      } 
      catch 
      { 
       Form2 ErrorPopup = new Form2(); 
       if (ErrorPopup.ShowDialog() == DialogResult.OK) 
       { 
        ErrorPopup.Dispose(); 
       } 
      } 

     } 

     private void Stop_Button_Click(object sender, EventArgs e) 
     { 
      LoopCheck = false; 
      timer1.Stop(); 
     } 

     private void timer1_Tick(object sender, EventArgs e) 
     { 
      textBox1.Text = WordToShow; 
     } 
    } 
} 

回答

0

代替Thread.Sleep(1000);使用async/await功能與Task.Delay爲了保持你的UI負責:

private async void Start_Button_Click(object sender, EventArgs e) 
    { 
     timer1.Interval = 100; 
     timer1.Enabled = true; 
     timer1.Start(); 
     LoopCheck = true; 
     try 
     { 
      while (LoopCheck) 
      { 
       foreach (string word in WordsOfFile) 
       { 
        WordToShow = word; 
        await Task.Delay(1000); 
       } 
      } 
     } 
     catch 
     { 
      Form2 ErrorPopup = new Form2(); 
      if (ErrorPopup.ShowDialog() == DialogResult.OK) 
      { 
       ErrorPopup.Dispose(); 
      } 
     } 

    } 
+0

這解決了這個問題。謝謝。但我不明白爲什麼有一個Thread.Sleep()方法,當我們有更可靠的這樣的? – Zgrkpnr