Threading


On creating a program  some of us are contented on using a simple way of coding without considering the best way on running on executing your program, one way is on loading a data from the database having a record with one million rows it takes time to load and it may freeze up your program.

Let’s say that we have a form that will load a data on a listview  having one column and 2 buttons and a textbox

The first button will have the code of this one creating a thread to run it on a separate  instance of the Form so that when it run it will not freeze up.
            Thread trd = new Thread(pop_lv);
            trd.Start();
 The convention on creating a thread is that you need to create a method that will be executed when the thread is called, pop_lv is a thread.
   private void main(string text)
        {        
              
                listView1.Items.Add(text);           
        }

This method is created to populate the listview base from the sended message from the sender.


delegate void SetTextCallback(string lv);
        private void pop_lv()
        {
           
        
            Thread.Sleep(100);
           if (! this.listView1.InvokeRequired)
            {

            
              
            }
            else
            {
                for (int i = 0; i < 100; i++)
                {
             

                    SetTextCallback d = new SetTextCallback(main);
                    this.Invoke(d, new object[] { i.ToString() });
                }
            }

        }

This code is done to do the thread in a different instance when this one is created the invokerequires gave us the permission to access listview from the different form or instance, and when invoke is requre the listview will be populated from 1 to 100.


listView1.Items.Add(textBox1.Text);

On the next button the user will just insert a record base from the input to the textbox



If you can observe is a big difference on coding this the same logic on not using a thread it’s up to you to appreciate it.. J

Walang komento:

Mag-post ng isang Komento