delegate Thread 的簡單使用

iDotNetSpace發表於2009-01-14

using System;
using System.Windows.Forms;
using System.Threading;

namespace _Delegate
{
  
    delegate void GetDelegate();
    delegate void DelegateStart();
    delegate void TimeSprogressStep(int index);
    delegate void DelegateFinished(string Message);
    public partial class Form1 : Form
    {
        Thread aThread;
        DelegateStart delegatestart;
        TimeSprogressStep timesprogressstep;
        DelegateFinished delegatefinished;
        static int icount = 0;
        int sum = 0;

        public Form1()
        {
            InitializeComponent();

            delegatestart = new DelegateStart(this.Start);
            timesprogressstep = new TimeSprogressStep(this.TimeSprogresStep);
            delegatefinished = new DelegateFinished(this.DelegateFinished);
        }
      
        private void btnThread(object sender, EventArgs e)
        {
            aThread = new Thread(new ThreadStart(this.thread_Ms));
            aThread.IsBackground = true;
            aThread.Start();          
        }

        private void Start()
        {
            this.lblcontent.Text = "";
            sum = 1000;
            this.timeprogressBar.Maximum = sum;
            this.button2.Enabled = false;
        }
        private void TimeSprogresStep(int index)
        {
            this.timeprogressBar.PerformStep();           
            this.lblcontent.Text = string.Format("Status:{0}",index);
        }

        private void DelegateFinished(string mess)
        {          
            this.button2.Enabled = true;
            this.timeprogressBar.Value = 0;
        }
        protected void thread_Ms()
        {
            icount = 0;
            this.Invoke(delegatestart);
                 
            while (icount < sum)
            {                               
                timeprogressBar.Invoke(this.timesprogressstep, new object[] { icount});
                Application.DoEvents();                
                icount++;
            }

            this.Invoke(this.delegatefinished, new object[] { "全部完成!"});
        }

        private void btnDelegate(object sender, EventArgs e)
        {
            GetDelegate mDelegate = new GetDelegate(this.thread_Ms);
            mDelegate();
        }
    }
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-539613/,如需轉載,請註明出處,否則將追究法律責任。