通过编写几个计算量较大的测试函数,通过线程调用的方式,实现同步计算,计算的过程中,需要对每个计算过程进行进度监控,并以进度条的形式展示,要避免程序假死等情况的出现。

解决方案 »

  1.   

    算是面试题吧。LZ大二,学校要求去公司实习,但我们的C#还没开课呢……这个怎么破?求大神帮助熬过这一关,我就可以跟在公司后面学习两个月了。
      

  2.   

    那就用多线程吧。有几个方法就开几个线程。
    开一个线程的方法:            Thread thread = new Thread(calculateMethod);
                thread.IsBackground = true;
                thread.Name = "Calculate";
                thread.Start();
      

  3.   

    使用backgroundWorker控件,此控件可以方便显示进度。
    如果使用多线程,就使用多个backgroundWorker控件。    public partial class Form1 : Form
        {
            /// <summary>
            /// 循环次数
            /// </summary>
            private int iLoopCnt = 100;        public Form1()
            {
                InitializeComponent();            backgroundWorker1.WorkerReportsProgress = true;
                backgroundWorker1.WorkerSupportsCancellation = true;
            }        private void btnStart_Click(object sender, EventArgs e)
            {
                progressBar1.Minimum = 0;
                progressBar1.Maximum = iLoopCnt;
                backgroundWorker1.RunWorkerAsync();
            }        private void btnStop_Click(object sender, EventArgs e)
            {
                backgroundWorker1.CancelAsync();
            }        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
            {
                BackgroundWorker bw = (BackgroundWorker)sender;
                for (int i = 0; i < iLoopCnt; i++)
                {
                    if (bw.CancellationPending == true)
                    {
                        e.Cancel = true;
                        break;
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(50);
                        bw.ReportProgress(i + 1);
                    }
                }
            }        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
                if (e.ProgressPercentage > progressBar1.Maximum)
                {
                }
                else
                {
                    progressBar1.Value = e.ProgressPercentage;
                }
            }        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Cancelled == true)
                {
                    MessageBox.Show("操作被取消!");
                }
                else if (e.Error != null)
                {
                    MessageBox.Show("操作时发生异常: " + e.Error.Message);
                }
                else
                {
                    //MessageBox.Show("操作已完成 ");
                }
            }