现在的位置: 首页 > 综合 > 正文

不错的线程使用示例

2013年04月19日 ⁄ 综合 ⁄ 共 12013字 ⁄ 字号 评论关闭
/// <copyright from='1997' to='2001' company='Microsoft Corporation'>
///    Copyright (c) Microsoft Corporation. All Rights Reserved.
///
///    This source code is intended only as a supplement to Microsoft
///    Development Tools and/or on-line documentation.  See these other
///    materials for detailed information regarding Microsoft code samples.
///
/// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Samples.Windows.Forms.Cs.ProgressBarCtl {
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Threading;

    // <doc>
    // <desc>
    //     This class demonstrates the ProgressBar control.
    //     The ProgressBar is updated periodically via another thread based on the
    //     settings in this control
    // </desc>
    // </doc>
    //
    public class ProgressBarCtl : System.Windows.Forms.Form {

        private System.ComponentModel.Container components;
        protected internal System.Windows.Forms.Label label3;
        protected internal System.Windows.Forms.Label lblCompleted;
        protected internal System.Windows.Forms.TrackBar sldrSpeed;
        protected internal System.Windows.Forms.ProgressBar progbar;
        protected internal System.Windows.Forms.Label label5;
        protected internal System.Windows.Forms.GroupBox grpBehavior;
        protected internal System.Windows.Forms.Label label4;
        protected internal System.Windows.Forms.Label label6;
        protected internal System.Windows.Forms.Label lblValue;
        protected internal System.Windows.Forms.ComboBox cmbStep;

        private int     iSleepTime ;
        private Thread  timedProgress ;

        public ProgressBarCtl() : base() {
            //
            // Required for Win Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            iSleepTime = 100 ;
            cmbStep.SelectedIndex = 0 ;
            progbar.Step = 1 ;

        }

        protected override void OnLoad(EventArgs e) {
            // Spin off a new thread to update the ProgressBar control
            timedProgress = new Thread(new ThreadStart(TimedProgressProc));
            timedProgress.IsBackground = true;
            timedProgress.Start();
        }

        // <doc>
        // <desc>
        //     This code executes on the Windows.Forms thread.
        // </desc>
        // </doc>
        //
        private void UpdateProgress() {
            int min ;
            double numerator, denominator, completed ;

            //Reset to start if required
            if (progbar.Value == progbar.Maximum) {
                progbar.Value = progbar.Minimum ;
            }
            else {
                
                progbar.PerformStep();
            }

            lblValue.Text = progbar.Value.ToString();

            min         = progbar.Minimum ;
            numerator   = progbar.Value - min ;
            denominator = progbar.Maximum - min ;
            completed   = (numerator / denominator) * 100.0 ;

            lblCompleted.Text = Math.Round(completed).ToString() + "%" ;
        }

        // <doc>
        // <desc>
        //     This function runs in the timedProgress thread and updates the
        //     ProgressBar on the form.
        // </desc>
        // </doc>
        //
        private void TimedProgressProc() {
            try {
                MethodInvoker mi = new MethodInvoker(UpdateProgress);
                while (true) {
                    Invoke(mi);
                    int iSleepTime = this.SleepTime;
                    Thread.Sleep(iSleepTime) ;
                }
            }
            //Thrown when the thread is interupted by the main thread - exiting the loop
            catch (ThreadInterruptedException e) {
                if (e != null) {}
            }
            catch (Exception we) {
                if (we != null) {
                    MessageBox.Show(we.ToString());
                }
            }
        }

        // <doc>
        // <desc>
        //     Property controlling the progress of the progress bar - used by the background thread
        // </desc>
        // </doc>
        //
        private int SleepTime {
            get {
                lock(this) {
                    return iSleepTime ;
                }
            }
            set {
                lock(this) {
                    iSleepTime = value ;
                }
            }
        }

        /// <summary>
        ///    Clean up any resources being used
        /// </summary>
        public override void Dispose() {
            /*
             * We have to make sure that our thread doesn't attempt
             * to access our controls after we dispose them.
             */
            if (timedProgress != null) {
                timedProgress.Interrupt();
                timedProgress = null;
            }

            base.Dispose();
            components.Dispose();
        }

        protected void sldrSpeed_Scroll(object sender, EventArgs e) {
            TrackBar tb = (TrackBar) sender ;
            int time = 110 - tb.Value ;
            this.SleepTime = time ;
        }

        protected void cmbStep_SelectedIndexChanged(object sender, EventArgs e) {
            try {
                progbar.Step = Int32.Parse((string)cmbStep.SelectedItem);
            }
            catch (Exception ex) {
                // thrown if Int32.Parse can't convert
                if (ex !=null) {}
            }
        }

        /// <summary>
        ///    Required method for Designer support - do not modify
        ///    the contents of this method with the code editor
        /// </summary>
        private void InitializeComponent() {
            this.lblValue = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.progbar = new System.Windows.Forms.ProgressBar();
            this.grpBehavior = new System.Windows.Forms.GroupBox();
            this.cmbStep = new System.Windows.Forms.ComboBox();
            this.label3 = new System.Windows.Forms.Label();
            this.sldrSpeed = new System.Windows.Forms.TrackBar();
            this.label6 = new System.Windows.Forms.Label();
            this.lblCompleted = new System.Windows.Forms.Label();
            this.grpBehavior.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.sldrSpeed)).BeginInit();
            this.SuspendLayout();
            //
            // lblValue
            //
            this.lblValue.Location = new System.Drawing.Point(164, 93);
            this.lblValue.Name = "lblValue";
            this.lblValue.Size = new System.Drawing.Size(72, 18);
            this.lblValue.TabIndex = 4;
            //
            // label4
            //
            this.label4.Location = new System.Drawing.Point(20, 93);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(288, 18);
            this.label4.TabIndex = 0;
            this.label4.Text = "Completion Speed:";
            //
            // label5
            //
            this.label5.Location = new System.Drawing.Point(31, 65);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(143, 28);
            this.label5.TabIndex = 1;
            this.label5.Text = "Percent Completed:";
            //
            // progbar
            //
            this.progbar.BackColor = System.Drawing.SystemColors.Control;
            this.progbar.Location = new System.Drawing.Point(31, 28);
            this.progbar.Name = "progbar";
            this.progbar.Size = new System.Drawing.Size(245, 18);
            this.progbar.Step = 1;
            this.progbar.TabIndex = 0;
            this.progbar.Text = "progbar";
            //
            // grpBehavior
            //
            this.grpBehavior.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                                      this.cmbStep,
                                                                                      this.label3,
                                                                                      this.sldrSpeed,
                                                                                      this.label4});
            this.grpBehavior.Location = new System.Drawing.Point(317, 19);
            this.grpBehavior.Name = "grpBehavior";
            this.grpBehavior.Size = new System.Drawing.Size(318, 175);
            this.grpBehavior.TabIndex = 5;
            this.grpBehavior.TabStop = false;
            this.grpBehavior.Text = "ProgressBar";
            //
            // cmbStep
            //
            this.cmbStep.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbStep.DropDownWidth = 123;
            this.cmbStep.Items.AddRange(new object[] {
                                                         "1",
                                                         "5",
                                                         "10",
                                                         "20"});
            this.cmbStep.Location = new System.Drawing.Point(174, 28);
            this.cmbStep.Name = "cmbStep";
            this.cmbStep.Size = new System.Drawing.Size(123, 20);
            this.cmbStep.TabIndex = 7;
            this.cmbStep.SelectedIndexChanged += new System.EventHandler(this.cmbStep_SelectedIndexChanged);
            //
            // label3
            //
            this.label3.Location = new System.Drawing.Point(20, 28);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(62, 18);
            this.label3.TabIndex = 6;
            this.label3.Text = "Step:";
            //
            // sldrSpeed
            //
            this.sldrSpeed.BackColor = System.Drawing.SystemColors.Control;
            this.sldrSpeed.Location = new System.Drawing.Point(20, 111);
            this.sldrSpeed.Maximum = 100;
            this.sldrSpeed.Minimum = 10;
            this.sldrSpeed.Name = "sldrSpeed";
            this.sldrSpeed.Size = new System.Drawing.Size(277, 42);
            this.sldrSpeed.TabIndex = 1;
            this.sldrSpeed.TabStop = false;
            this.sldrSpeed.Text = "trackBar1";
            this.sldrSpeed.TickFrequency = 10;
            this.sldrSpeed.Value = 10;
            this.sldrSpeed.Scroll += new System.EventHandler(this.sldrSpeed_Scroll);
            //
            // label6
            //
            this.label6.Location = new System.Drawing.Point(31, 93);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(128, 18);
            this.label6.TabIndex = 3;
            this.label6.Text = "Value:";
            //
            // lblCompleted
            //
            this.lblCompleted.Location = new System.Drawing.Point(164, 65);
            this.lblCompleted.Name = "lblCompleted";
            this.lblCompleted.Size = new System.Drawing.Size(72, 18);
            this.lblCompleted.TabIndex = 2;
            //
            // ProgressBarCtl
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.ClientSize = new System.Drawing.Size(647, 202);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.grpBehavior,
                                                                          this.lblValue,
                                                                          this.label6,
                                                                          this.lblCompleted,
                                                                          this.label5,
                                                                          this.progbar});
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "ProgressBarCtl";
            this.Text = "ProgressBar";
            this.Load += new System.EventHandler(this.ProgressBarCtl_Load);
            this.grpBehavior.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.sldrSpeed)).EndInit();
            this.ResumeLayout(false);

        }

        // The main entry point for the application.
        [STAThread]
        public static void Main(string[] args) {
            Application.Run(new ProgressBarCtl());
        }

        private void ProgressBarCtl_Load(object sender, System.EventArgs e)
        {

        }

    }

}

抱歉!评论已关闭.