thread 傳參數 和 回呼填回畫面UI

  • 1746
  • 0

摘要:thread 傳參數 和 回呼填回畫面UI

如果不使用回呼方式填回主thread UI 物件, 會出現 "跨執行緒作業無效" 的錯誤 

 


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

namespace GlobalReport
{
    

    public partial class ShipperMapping : Form
    {
        public ShipperMapping()
        {
            InitializeComponent();            
        }
        //把物件啟動跟資料讀取由不同的Thread 發動
        public void LoadData(){
            work w = new work(gridControl1,gridControl2,myBindData);            
            System.Threading.Thread oth = new System.Threading.Thread(new System.Threading.ThreadStart( w.DoMoreWork ) );
            oth.Start();  
        }
        
        // 回呼需要先宣告參數型態  (delegate method)
        public delegate void MYThreadBindData(DataSet ds, DevExpress.XtraGrid.GridControl gctrl);
        // 撰寫 method 實體 , 寫法是固定的
        public void myBindData(DataSet ds, DevExpress.XtraGrid.GridControl gctrl)
        {            
            if (this.InvokeRequired) 
            {
                MYThreadBindData obj = new MYThreadBindData(myBindData);  
                this.Invoke(obj ,ds, gctrl); // 第一個參數是回呼物件, 其他參數是回呼method 需要的參數         
            }else{
                gctrl.DataSource = ds.Tables[0];// 同thread 時的UI給值方式
            }
        }            

        // thread 物件sample
        class work
        {
            private DevExpress.XtraGrid.GridControl g1;
            private DevExpress.XtraGrid.GridControl g2;
            private MYThreadBindData binddata;
            
            //傳參數到Thread 裡面
            public work(DevExpress.XtraGrid.GridControl gridControl1, DevExpress.XtraGrid.GridControl gridControl2,MYThreadBindData m )
            {
                g1 = gridControl1;
                g2 = gridControl2;
                binddata = m;
            }
            
            public void DoMoreWork()
            {
                string sSQL = "select A.ship_cd, A.s_name , (SELECT ShowName from global_summary_top_mapp m where m.ship_cd = A.ship_cd)ShowName"
                    + " from (select distinct ship_cd, s_name from global_summary_top2)A ";
                WebServiceEncodeLib ws = new WebServiceEncodeLib();
                DataSet ds = ws.getDataSetXml(sSQL);                
                // 使用thread 回呼外部UI
                binddata(ds, g1);
                binddata(ds, g2);
            }
        }  

    }
}