C# invoke和begininvoke的用法 __委托


namespace invoke和begininvoke的用法
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //聲明接受int的方法並返回空的委托。
        public delegate void invokeDelegate();
        //調用委托,
        // invokeDelegate FF = new invokeDelegate(StartMethod);

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "主線程1 最先執行"); // 最先執行
            Thread invokeThread = new Thread(new ThreadStart(StartMethod)); //委托創建線程
            invokeThread.Start(); //開始線程


            string a = string.Empty;
            for (int i = 0; i < 10; i++)      //調整循環次數,看的會更清楚
            {
                Thread.Sleep(1000);
                a = a + "循環執行";
            }
            MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() +"主線程1"+ a);
            
        }

        private void StartMethod()
        {
            MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "主線程1 第二執行");
            button1.Invoke(new invokeDelegate(invokeMethod)); //傳遞一個委托的方法;  依賴此控件來執行委托
            //Thread.Sleep(3000);
            MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "子線程1");
        }
        private void invokeMethod()
        {
            //Thread.Sleep(5000);
            MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "主線程1 _執行委托方法");
        }
    }
}

來源 https://www.cnblogs.com/lsgsanxiao/p/5523282.html;

 

 

線程初始化方法

 

--委托

        public delegate int MyDelegate(string s);  //聲明委托 // 類似於函數指針  返回值 為int 的函數,
        //定義一個與這個委托相對應的函數
        public static int AddNum(string str)
        {
            return 0;
        }
        //自定義一個  函數 來 
        public void exc_delegate() {

            // 創建委托實例
            MyDelegate nc1 = new MyDelegate(AddNum);
            nc1(string.Empty); //執行該函數
        }

---調用控件線程

        public delegate void UpdateListBoxCallback(string strAlarmTime, string strDevIP, string strAlarmMsg);
         
if (InvokeRequired) { object[] paras = new object[3]; paras[0] = DateTime.Now.ToString(); //當前PC系統時間 paras[1] = strIP; paras[2] = sb.ToString(); listViewAlarmInfo.BeginInvoke(new UpdateListBoxCallback(UpdateClientList), paras); }
      public void UpdateClientList(string strAlarmTime, string strDevIP, string strAlarmMsg)
        {
            //列表新增報警信息
            listViewAlarmInfo.Items.Add(new ListViewItem(new string[] { strAlarmTime, strDevIP, strAlarmMsg }));
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM