Note that there are some explanatory texts on larger screens.

plurals
  1. POSimple multithreaded program in C# not working
    text
    copied!<p>I am trying to write a simple multithreaded program in C#. It has a button pressing which creates a new label on form, and then a for loop runs displaying loop value in label. So if you press button 3 times, it will create 3 threads with 3 labels on form with loop.</p> <p>When I press the button once, it works fine. But when I press it more than once to create more labels, it runs into following problems:</p> <ol> <li><p>As soon as button is pressed more than once, it stops the loop in previous thread and runs loop of new thread. If it is multithreaded then it should not stop first loop.</p></li> <li><p>When loop of second label is finished, it gives following error</p></li> </ol> <blockquote> <p>Object reference not set to an instance of an object</p> </blockquote> <p>Here is my complete code. The line which throws error is at the end "mylabel[tcount].Text = i.ToString();".</p> <p>Screenshot of program: <a href="http://i.imgur.com/IFMIs.png" rel="nofollow">http://i.imgur.com/IFMIs.png</a></p> <p>Screenshot of code <a href="http://i.imgur.com/sIXtc.png" rel="nofollow">http://i.imgur.com/sIXtc.png</a></p> <pre><code>namespace WindowsFormsApplication2{ public partial class Form1 : Form{ public Form1(){ InitializeComponent(); } private int tcount = 0; private int y_point = 0; Thread[] threads = new Thread[5]; Label[] mylabel = new Label[5]; private void button1_Click(object sender, EventArgs e){ threads[tcount] = new Thread(new ThreadStart(work)); threads[tcount].Start(); } private void work(){ if (this.InvokeRequired){ this.Invoke(new MethodInvoker(delegate{ mylabel[tcount] = new Label(); mylabel[tcount].Text = "label" + tcount; mylabel[tcount].Location = new System.Drawing.Point(0, y_point + 15); y_point += 25; this.Controls.Add(mylabel[tcount]); for (int i = 0; i &lt; 10000; i++){ mylabel[tcount].Text = i.ToString(); Application.DoEvents(); } })); } tcount++; } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload