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 }));
        }

 

posted @ 2018-11-19 17:30  enych  阅读(2461)  评论(0编辑  收藏  举报