日期:2014-05-17  浏览次数:20423 次

如何使用BackgroundWorker增加多个线程
已经会使用BackgroundWorker增加后台线程,但问题是只有一个线程,访问1到1000要好几秒,速度还不会很快,我想利用BackgroundWorker增加线程,1秒之内搞定,请问如下代码如何改造呢?


BackgroundWorker bw = null;

        public Form5()
        {
            InitializeComponent();

            bw = new BackgroundWorker();
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 1; i < 1000; i++)
            {
                if (bw.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                this.Invoke((MethodInvoker)delegate
                {
                    this.ShowText(String.Format("第{0}步正在执行", i));
                });
            }
        }

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.ShowText("执行完毕!");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.button1.Enabled = false;
            this.button2.Enabled = true;

            bw.RunWorkerAsync();
        }

        private void button2_Click(object sender, EventArgs e)
        {
    &nb