invoke和begininvoke的用法 多线程??

        //声明接受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 _执行委托方法");
        }

        static void GetFile(string s)
        {
            try
            {
                FileInfo fi = new FileInfo(s);
                Console.WriteLine("文件路径:{0}", s);
                Console.WriteLine("文件名称:{0}", fi.Name.ToString());
                Console.WriteLine("文件类型:{0}", fi.Extension.ToString());
                Console.WriteLine("文件大小:{0} K", fi.Length / 1024);
                Console.WriteLine("文件创建时间:{0}", fi.CreationTime.ToString());
                Console.WriteLine("上次访问时间:{0}", fi.LastAccessTime.ToString());
                Console.WriteLine("上次写入时间:{0}", fi.LastWriteTime.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

 

posted @ 2020-03-27 17:44  enych  阅读(291)  评论(0编辑  收藏  举报