美文网首页
C#多线程异步执行耗时

C#多线程异步执行耗时

作者: 陈弟CD | 来源:发表于2017-05-26 18:04 被阅读466次
           // 界面的控件button , label, progressBar, statusStrip中的toolStripProgressBar
            public Form1()
            {
                InitializeComponent();
            }
    
            long number = 0;
            DateTime beginDate;    //记时 
            DateTime endDate;
            private void button1_Click(object sender, EventArgs e)
            {
                beginDate = DateTime.Now;// 记录当前时间
                number = 0;
                this.label1.Text = "label1";
                this.progressBar1.Value = 0;
                this.button1.Enabled = false;
    
                Thread thread = new Thread(new ThreadStart(myFun));
                thread.Name = "thread1";
                thread.IsBackground = true;
                thread.Start();
            }
    
           // 耗时操作
            private void myFun()
            {
                for (int i = 0; i < 100000000; i++)
                {
                    number += i;
                }
                if (this.InvokeRequired)//进行判断
                {
                    this.BeginInvoke(new Test(this.sum)); //显示到界面上
                }
                else
                {
                    sum();
                }
            }
    

    delegate

            delegate void Test();
    
            private void sum()
            {
                endDate = DateTime.Now;
                System.TimeSpan timeSpan = endDate - beginDate;
                progressBar1.Maximum = timeSpan.Milliseconds;
    
                toolStripProgressBar1.Maximum = timeSpan.Milliseconds;
    
                for (int i = 0; i <= timeSpan.Milliseconds; i++)
                {
                    progressBar1.Value = i;
                    toolStripProgressBar1.Value = i;
                    Application.DoEvents();
                }
    
                this.label1.Text = number.ToString();
                this.button1.Enabled = true;
            }
    

    相关文章

      网友评论

          本文标题:C#多线程异步执行耗时

          本文链接:https://www.haomeiwen.com/subject/evmxfxtx.html