我有richTextBox1和richTextBox2它将获取richTextBox1中的每一行并使用多线程显示到richTextBox2,由numericUpDown1设置的线程数。例如,我将数据粘贴到richTextBox1并在numericUpDown1中设置5个线程,它可以在从第一行到最后一行的循环中工作,但是当
ptr = list.Length时它不会在循环和错误中断开
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;
}
}
}
}
答案 0 :(得分:2)
问题是你检查ptr是否小于数组长度&amp;在使用之前立即增加它。 应该是
if (ptr < list.Length-1)
{
ptr += 1;
或者在递增之前使用ptr。