Multi-thread for UI

Multi-thread for UI

轉貼:

http://www.dotblogs.com.tw/atowngit/archive/2010/01/05/12810.aspx
http://www.dotblogs.com.tw/ricochen/archive/2009/12/12/12392.aspx


{
    DataTable dt;
    bool flag;

    private void InitData()
    {
        dt = new DataTable("table1");
        dt.Columns.Add("c1");
        dt.Columns.Add("c2");
        Random rnd = new Random();
        for (Int32 i = 1; i <= 10; i++)
        {
            DataRow row = dt.NewRow();
            row["c1"] = rnd.Next(1, 100);
            row["c2"] = "i_am_c2";
            dt.Rows.Add(row);
        }
        dataGridView1.DataSource = dt;
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        InitData();
        System.Threading.ThreadPool.SetMinThreads(2, 5);
        System.Threading.ThreadPool.SetMaxThreads(4, 10);
    }

    //宣告delegate
    delegate void MyInvoke(String status);
    private void UpdateLab(String status) { label1.Text = status; }

    delegate void MyInvoke2(Int32 index);
    private void DisplayDgv(Int32 index) { dataGridView1.FirstDisplayedScrollingRowIndex = index; }

    private void AddRow()//object arg 
    {
        if (flag)
        {
            for (Int32 i = 1; i <= 100000; i++)
            {
                DataRow dr = dt.NewRow();
                dr["c1"] = i.ToString();
                dr["c2"] = "hello";
                dt.Rows.Add(dr);

                MyInvoke mi = new MyInvoke(UpdateLab);

                //使用主緒更新Label
                Invoke(mi, "總共筆數:" + dt.Rows.Count.ToString());
                //UpdateLab("總共筆數:" + dt.Rows.Count.ToString());

                System.Threading.Thread.Sleep(1);

                if (i % 500 == 0)
                {
                    MyInvoke2 mi2 = new MyInvoke2(DisplayDgv);
                    //使用主緒更新DataGridView
                    Invoke(mi2, i);
                    //DisplayDgv(i);
                }
            }
        }
        else
            return;
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        flag = true;
        //單一執行緒
        //AddRow();

        //使用其它 Thread 處理新增資料作業
        //下列兩種方法皆可
        //1. 將 "新增資料作業" 的 Thread 丟入 ThreadPool Queue 等待執行 (此方式所執行的方法一定要帶有 object 參數)
        //System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(AddRow));
        //2. 建立新的 Thread 執行 "新增資料作業", 在 call Start() 後即會將該 Thread 丟入 ThreadPool Queue 等待執行
        new System.Threading.Thread(new System.Threading.ThreadStart(AddRow)).Start();
    }
}