博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

backgroundWorker1

Posted on 2011-04-07 23:17  moss_tan_jun  阅读(211)  评论(0编辑  收藏  举报

 

 

 private void button3_Click(object sender, EventArgs e)
        {
            string str = this.textBox2.Text.Trim();
           
           this.backgroundWorker1.RunWorkerAsync(str);
           
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = (BackgroundWorker)sender;

            string url = e.Argument.ToString();

            for (int i = 1; i <= 10; i++)
            {
                //没有取消后台操作
                if (!bw.CancellationPending)
                {
                    WebRequest req = WebRequest.Create(url);
                    WebResponse resp = req.GetResponse();
                    resp.Close();

                    Thread.Sleep(100);
                    bw.ReportProgress(i * 100 / 10, i);
                }
            }


        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            label1.Text = e.UserState.ToString() + "/10";
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("OK");
        }