小小线程记【转】

//1 全局定义
        int m_fileName;
        Thread m_thread;
        FileInfo[] filelist;
        // 定义进度条操作的委托函数原形
        public delegate void MyOption(int value);

        public Form6()
        {
            InitializeComponent();
        }


        //3 定义线程处理函数
        private void myProc()
        {
            for (int n = 0; n < filelist.Length; n++)
            {
                //Thread.Sleep(5000);
                string dd = @"D:\j\" + filelist[n];
                filelist[n].CopyTo(dd);
                this.Invoke(new MyOption(myOption), n);
            }
            ////处理Excel循环
            //for (int i = 0; i < m_fileName; i++)
            //{
            //    //执行SQL操作
            //    // 在线程中操作窗体控件,必须使用窗体的Invoke函数来执行,否则会有异常。
            //    this.Invoke(new MyOption(myOption), i);
            //}
        }

        //4 进度条处理
        private void myOption(int value)
        {
            this.progressBar1.Value = value;
            value += 1;
            label1.Text = value.ToString() + "/" + filelist.Length;
            if (value == this.progressBar1.Maximum)
            {
                MessageBox.Show("复制完成");
                this.progressBar1.Visible = false;
            }
        }

        private void Form6_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog f1 = new FolderBrowserDialog();
            if (f1.ShowDialog() == DialogResult.OK)
            {
                DirectoryInfo di = new DirectoryInfo(f1.SelectedPath);
                filelist = di.GetFiles("*.jpg");

                //2 处理按钮事件触发函数
                m_fileName = filelist.Length;
                m_thread = new Thread(new ThreadStart(myProc));
                m_thread.Start();
                this.progressBar1.Maximum = m_fileName;
                this.progressBar1.Minimum = 0;
                this.progressBar1.Value = 0;
            }
        }
posted on 2008-08-12 17:15  草原和大树  阅读(558)  评论(0编辑  收藏  举报