Thanh Nguyen
Thanh Nguyen

Reputation: 83

How to exit while loop in multithread c#

i have richTextBox1 and richTextBox2 it will get each line in richTextBox1 and show into richTextBox2 using multithread, number of thread set by numericUpDown1. ex i paste data into richTextBox1 and set 5 thread in numericUpDown1 it works while loop from first line to last line but when

ptr = list.Length
it doesn't break while loop and error

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;
            }
        }
    }
}

Upvotes: 0

Views: 175

Answers (1)

PaulF
PaulF

Reputation: 6773

The problem is you check the ptr to be less than array length & immediately increment it before using it. Should be

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

Or use ptr before incrementing it.

Upvotes: 2

Related Questions