0

I get an error in my code:

Cross-thread operation not valid: Control 'listBox1' accessed from a thread other than the thread it was created on

Code:

 private void button2_Click(object sender, EventArgs e)
 {
     Thread t1 = new Thread(mult);
     t1.Start();
 }
 public void mult()
 {
     FileStream fq = new FileStream(textBox1.Text, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
     StreamReader s = new StreamReader(fq);
     while (!s.EndOfStream)
     {
         Thread.Sleep(500);
         listBox1.Items.Add(s.ReadLine()); //error at this line

     }

     s.Close();
Prix
  • 19,417
  • 15
  • 73
  • 132
Ash
  • 57
  • 9

2 Answers2

0

In DOT-NET, you cannot modify UI elements from user-created threads. Only the primary thread (which created the control) is allowed to modify it. That means, from within the new thread you cannot update the list box entries.

there are other strategies like BackgroundWorker. plese see the link @Rotem posted and also google up BackgroundWorker.

Update: If you follow the link and decide to go the ListBox1.Invoke() way, then I would suggest using BeginInvoke in place of Invoke.

inquisitive
  • 3,549
  • 2
  • 21
  • 47
0

Put the listbox updating around this.

this.Invoke(new MethodInvoker(delegate()
{
 //stuff
}));
ismellike
  • 629
  • 1
  • 5
  • 14