2015-07-10 31 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。