.net通过BackgroundWorker类实现多线程编程

前面学习了async/await特性来异步处理任务,BackgroundWorker可以在需要另建一个线程,并且后台持续的完成某项工作,而且可以和主线程进行交互通信。

参考文档:

https://msdn.microsoft.com/zh-cn/library/system.componentmodel.backgroundworker.aspx

代码示例:

    class Program
    {
        static void Main(string[] args)
        {
            BackgroundWorkerTest test = new BackgroundWorkerTest();
            test.bgWorkerBeginRun();
            Thread.Sleep(3000);
            Debug.WriteLine("主线程的挂起不影响BackgroundWorker");
            Console.WriteLine("中断后台程序运行请输入:t");
            var str = Console.ReadKey();
            if (str.KeyChar == 't')
            {
                test.bgWorkerCancel();
                Console.WriteLine("手动取消BackgroundWorker程序运行");
            }
            Console.WriteLine("结束运行");
            Console.ReadKey();
        }
    }
    class BackgroundWorkerTest
    {
        Stopwatch watch = new Stopwatch();
        BackgroundWorker bgWorker = new BackgroundWorker();
        public BackgroundWorkerTest()
        {
            watch.Start();
            bgWorker.WorkerReportsProgress = true; //能否报告进度更新
            bgWorker.WorkerSupportsCancellation = true;//是否支持异步取消
            //BackgroundWorker对象的处理程序
            bgWorker.DoWork += DoWork_Handler;//调用RunWorkerAsync时发生
            bgWorker.ProgressChanged += ProgressChanged_Handler;//调用ReportProgress(Int32)时发生
            bgWorker.RunWorkerCompleted += RunWorkerCompleted_Handler;//当后台操作已完成、被取消或引发异常时发生
        }
        public void bgWorkerBeginRun()
        {
            if (!bgWorker.IsBusy)
                bgWorker.RunWorkerAsync(); //开始执行后台操作
            else
                Debug.WriteLine("bgWorker正在运行,不能开始!");
        }
        public void bgWorkerCancel()
        {
            bgWorker.CancelAsync(); //请求取消挂起的后台操作
        }
        private void DoWork_Handler(object sender, DoWorkEventArgs args)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 0; i <= 10; i++)
            {
                if (worker.CancellationPending) //是否请求取消了后台操作
                {
                    args.Cancel = true; //获取或设置指示是否应取消事件的值
                    break;
                }
                else
                {
                    worker.ReportProgress(i * 10); //引发ProgressChanged世界
                    Thread.Sleep(1000);
                }
            }
        }
        private void ProgressChanged_Handler(object sender, ProgressChangedEventArgs args)
        {
            Debug.WriteLine("当前进度" + args.ProgressPercentage + "%");
        }
        private void RunWorkerCompleted_Handler(object sender, RunWorkerCompletedEventArgs args)
        {
            Debug.WriteLine("触发RunWorkerCompleted");
            if (args.Cancelled)
                Debug.WriteLine("进度条取消");
            else
                Debug.WriteLine("进度条完成");
        }
    }
执行代码,如下的结果:
当前进度0%
当前进度10%
当前进度20%
主线程的挂起不影响BackgroundWorker
当前进度30%
当前进度40%
当前进度50%
当前进度60%
当前进度70%
当前进度80%
当前进度90%
当前进度100%
触发RunWorkerCompleted
进度条完成
BackgroundWorker类主要用于GUI编程。
posted @ 2018-04-05 19:57  huey-chan  阅读(215)  评论(0编辑  收藏  举报