Tuesday, October 16, 2018

C# multiple thread updating winform listbox items parallel processing

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

namespace IndicatorUpdator
{
    public partial class Form1 : Form
    {
        SqlConnection cnn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connection"].ConnectionString);

        public Form1()
        {
            InitializeComponent();
            GetSymbols();
        }

        public void GetSymbols()
        {
            if (cnn.State == ConnectionState.Closed)
            {
                listBox1.Items.Insert(0, " try to open, connection stat:" + cnn.State.ToString());
                cnn.Open();
            }
            else
            {
                listBox1.Items.Insert(0, " already open, connection stat:" + cnn.State.ToString());

            }
            if (cnn.State == ConnectionState.Broken)
            {
                listBox1.Items.Insert(0, "***** broken connection stat:" + cnn.State.ToString());

            }

            listBox1.Items.Insert(0, " connection stat:" + cnn.State.ToString());
            String q1 = "select table_name from information_schema.tables";
            SqlCommand c1 = new SqlCommand(q1, cnn);

            using (var reader = c1.ExecuteReader())
            {
                while (reader.Read())
                {
                    //exist insert record
                    lbSymbol.Items.Insert(0,reader.GetString(0));
                }
            }


        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            System.Threading.Tasks.Parallel.For(0, lbSymbol.Items.Count, i =>
            {
                //Thread.Sleep(1000);
                //int j = i;
                //listBox1.Invoke(() => listBox1.Items.Insert(0, j));

              // below can access winform listbox control from different thread
                this.Invoke((MethodInvoker)delegate
               {
                   this.listBox1.Items.Insert(0, i);
               });
                //So stuff with i

                //Console.WriteLine("i: " + i);
            });
        }
    }
}

No comments:

Post a Comment