2015-07-10 62 views
0

我有richTextBox1和richTextBox2它將獲取richTextBox1中的每一行,並使用多線程,使用多線程,由numericUpDown1設置的線程數顯示到richTextBox2。 EX I數據粘貼到richTextBox1並設置5線程NumericUpDown1中它的工作原理while循環,從第一行到最後一行,但是當如何退出while循環多線程c#

ptr = list.Length
不while循環和錯誤

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in Test.exe 

Additional information: Index was outside the bounds of the array.
public partial class Form1 : Form 
{ 
    bool continueThreads = false; 
    int ptr = 0; 
    string[] list = null; 
    List<Thread> threadList = new List<Thread>(); 
    int finished = 0; 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     int n = (int)numericUpDown1.Value; 
     Thread[] tl = new Thread[n + 1]; 
     threadList = tl.ToList(); 
     for (int i = 0; i <= n; i++) 
     { 
      threadList[i] = new Thread(new ThreadStart(getlist)); 
     } 
     for (int i = 0; i <= n; i++) 
     { 
      threadList[i].Start(); 
     } 
     richTextBox2.Text = ""; 
     ptr = 0; 
     finished = 0; 
     continueThreads = true; 
     list = richTextBox1.Lines; 
    } 

    public void getlist() 
    { 
     while (continueThreads) 
     { 
      if (ptr < list.Length) 
      { 
       ptr += 1; 
       string info = ""; 
       info += "Get " + list[ptr] + Environment.NewLine; 
       Thread.Sleep(1000); 
       this.Invoke(new Action(() => richTextBox2.Text += info)); 
      } 
      else 
      { 
       continueThreads = false; 
       break; 
      } 
     } 
    } 
} 

回答

2

問題是你查破ptr小於數組長度&在使用之前立即增加它。 應該是

if (ptr < list.Length-1) 
    { 
     ptr += 1; 

或者在增加它之前使用ptr。