码迷,mamicode.com
首页 > 编程语言 > 详细

C# Backgroundworker(后台线程)的使用

时间:2016-08-02 14:50:33      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:

namespace BackgroundWorkderPauseSample
{
    public partial class MainForm : Form
    {
        BackgroundWorker worker = null;

        public MainForm()
        {
            InitializeComponent();
            Load += new EventHandler(Form1_Load);
        }

        void Form1_Load(object sender, EventArgs e)
        {
            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
                MessageBox.Show("用户取消了操作");
            else
            {
                MessageBox.Show("正常完成了操作");
            }

        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 100; i++)
            {
                if (worker.CancellationPending)//如果用户申请取消
                {
                    for (int k = i; k >= 0; k--)
                    {
                        Thread.Sleep(10);
                        worker.ReportProgress(k);//模拟一个回滚的效果
                    }
                    e.Cancel = true;
                    return;
                }

                manualReset.WaitOne();//如果ManualResetEvent的初始化为终止状态(true),那么该方法将一直工作,直到收到Reset信号。然后,直到收到Set信号,就继续工作。
                //反之亦然
                Thread.Sleep(500);
                worker.ReportProgress(i+1);

            }
        }

        private void btStart_Click(object sender, EventArgs e)
        {
            worker.RunWorkerAsync();
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            worker.CancelAsync();
        }


        private ManualResetEvent manualReset = new ManualResetEvent(true);

        private void btPause_Click(object sender, EventArgs e)
        {
            if (btPause.Text == "暂停")
            {
                manualReset.Reset();//暂停当前线程的工作,发信号给waitOne方法,阻塞
                btPause.Text = "继续";
            }
            else
            {
                manualReset.Set();//继续某个线程的工作
                btPause.Text = "暂停";
            }
        }
    }
}

技术分享

C# Backgroundworker(后台线程)的使用

标签:

原文地址:http://www.cnblogs.com/a849788087/p/5729122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!