异步操作--BackgroundWorker应用

 
 

using System;

using System.ComponentModel;

using System.Threading;

using System.Windows.Forms;

 

namespace BackgroundWorkerExample

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        //若要设置后台操作,请为 DoWork 事件添加一个事件处理程序,此例中的     TimeConsumingOperation

        //在此事件处理程序中调用耗时的操作

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

        {

            // 必须非常小心,确保在 DoWork 事件处理程序中不操作任何用户界面对象。ProgressChanged //RunWorkerCompleted 事件与用户界面进行通信。

            // 不要直接使用Form上的BackgroundWorker引用.

            // 而使用sender参数提供的引用.

            BackgroundWorker bw = sender as BackgroundWorker;

            // 获取 argument 属性(object 表示异步操作参数).

            int arg = (int) e.Argument;

            // 为异步操作结果获取一个操作.

            e.Result = TimeConsumingOperation(bw, arg);

            // 加入这个异步操作被用户取消,

            // 设置the DoWorkEventArgs.Cancel 为真.

            if (bw.CancellationPending)

            {

                e.Cancel = true;

            }

        }

 

        //在操作完成时收到通知,对 RunWorkerCompleted 事件进行处理。

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

        {

            if (e.Cancelled)

            {

                // 用户取消操作

                MessageBox.Show("Operation was canceled");

            }

            else if (e.Error != null)

            {

                // 操作期间发生一个错误

                string msg = String.Format("An error occurred: {0}", e.Error.Message);

                MessageBox.Show(msg);

            }

            else

            {

                // 操作正常完成

                string msg = String.Format("Result = {0}", e.Result);

                MessageBox.Show(msg);

            }

        }

 

        // 这是一个可能花一段时间运行的操作

        // 它能被取消,能抛出一个异常,

        // 也能归还一个结果.

        private int TimeConsumingOperation(BackgroundWorker bw, int sleepPeriod)

        {

            int result = 0;

            Random rand = new Random();

            //获取一个值,指示应用程序是否已经取消后台操作

            while (!backgroundWorker1.CancellationPending)

            {

                bool exit = false;

                switch (rand.Next(3))

                {

                        // 抛出一个异常

                    case 0:

                        {

                            throw new Exception("An error condition occurred.");

                            break;

                        }

                    case 1:

                        {

                            Thread.Sleep(sleepPeriod);

                            break;

                        }

                        // 正常退出.

                    case 2:

                        {

                            result = 23;

                            exit = true;

                            break;

                        }

                    default:

                        {

                            break;

                        }

                }

                if (exit)

                {

                    break;

                }

            }

            return result;

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            //启动backgroundWorker1_DoWork中的事件处理程序,此例中的TimeConsumingOperation

            backgroundWorker1.RunWorkerAsync(2000);

        }

 

        private void button2_Click(object sender, EventArgs e)

        {

            backgroundWorker1.CancelAsync();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            //组件支持取消操作

            this.backgroundWorker1.WorkerSupportsCancellation = true;

        }

    }

}

//如果后台操作需要参数,请在调用 RunWorkerAsync 时给出参数。在 DoWork 事件处理程序内部,

//可以从 DoWorkEventArgs.Argument 属性中提取该参数。

 
 
 

转载于:https://www.cnblogs.com/blue-th/archive/2008/09/25/1298584.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值