Click here to Skip to main content
15,434,147 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two list boxes ,one works on UI thread and another I need to work on another thread.First List box is populated with UI thread,after adding the full elements I need to add those elements into another list box using another .What should I do for this.I have codded for this but I get an error like Invoke or BeginInvoke cannot be called on a control until the window handle has been created. I may put code snippet I have written

Thanks and Regards

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace ThreadApplication
    public partial class Form1 : Form
        public Form1()

        private void button1_Click(object sender, EventArgs e)

            label1.Text = Thread.CurrentThread.Name;
            string[] fruits;
            fruits = new string[5];
            fruits[0] = "Banana";
            fruits[1] = "Grape";
            fruits[2] = "Apple";
            fruits[3] = "Orange";
            fruits[4] = "Pappaya";

            foreach (var fruit in fruits)

            var list = new ArrayList();

             Thread  objNewThread = new Thread(new ParameterizedThreadStart(objAddFruits.ConsumerJob));

             MessageBox.Show("" + Thread.CurrentThread.Priority);

            catch (Exception ex)
                MessageBox.Show("" + ex.Message);


        private void button2_Click(object sender, EventArgs e)
           //new ConsumerJobClass().ConsumerJob();

    public  class ConsumerJobClass :Form1

        public  void ConsumerJob(object list)
            var frm=new Form1();
           ArrayList arrayList=(ArrayList)list;
         foreach (var item in arrayList)
               if (!frm.IsHandleCreated)
 frm.listBox2.Invoke((MethodInvoker)delegate() { frm.listBox2.Items.Add(item); }); // I got Error here
                this.Invoke(new Action(() => listBox1.Items.Remove(item)));



Updated 16-Apr-14 0:15am

1 solution

Don't even try to do it like that.
For starters, it won't work: you create a new instance of the form in your ConsumerJob method, so even if it did work it wouldn't update the display.

Instead, consider using a BackgroundWorker class instead: it provides a mechanism for feeding progress back to the form that originated the thread via the ProgressChanged Event, and that infor can include the e.UserState object - which can contain the data you want to update the listboxes with.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900