views:

987

answers:

3

Hi everyone.

I'm trying to use a Thread in a simple winform. I have a ListBox which I want to fill with numbers at the form's load method. I don't want to wait until it is filled. I'm using something like this:

void fillList()
     {

      Invoke(new MethodInvoker(
       delegate
       {
        while(true)
        {
         i++;
         listBox1.Items.Add(i);
         if(i == 4000)
         break;


        }  
       }));

     }

Then at the Load method I'm doing this:

Thread tr = new Thread(fillList());
tr.Start();

Why it isn't working?

I get this error: Method name expected (CS0149)

Thanks.

+2  A: 

Thread tr = new Thread(fillList);

Ed Guiness
+3  A: 

Invoke will just run the above back on the UI thread which is already happening if you are calling this from the form load, so your UI will still be held up while you populate the list.

In the above example, you probably don't need a new thread, just create an array, fill it and then do an AddRange instead of the Add.

The Add causes a refresh every time and that is what is slowing down your load. With AddRange the refresh will only happen once.

Rob Prouse
A: 

Thanks. I did this way (Add) because i wanted to test Threads in UI. Thanks for those tips.