bandariiswear

幽艳纷相竞 秾纤各自奇 虽然春烂漫 也要笔扶持 清人题画诗

导航

winform异步进度条LongTime

winform异步进度条LongTime,运用到回调函数

定义事件的参数类:

namespace LongTime.Business
{
    // 定义事件的参数类
    public class ValueEventArgs 
        : EventArgs
    {
        public int Value { set; get;}
    }

    // 定义事件使用的委托
    public delegate void ValueChangedEventHandler( object sender, ValueEventArgs e);

    class LongTimeWork
    {
        // 定义一个事件来提示界面工作的进度
        public event ValueChangedEventHandler ValueChanged;

        // 触发事件的方法
        protected void OnValueChanged( ValueEventArgs e)
        {
            if( this.ValueChanged != null)
            {
                this.ValueChanged( this, e);
            }
        }

        public void LongTimeMethod()
        {
            for (int i = 0; i < 100; i++)
            {
                // 进行工作
                System.Threading.Thread.Sleep(1000);

                // 触发事件
                ValueEventArgs e = new ValueEventArgs() { Value = i+1};
                this.OnValueChanged(e);
            }
        }
    }
}
View Code

WINFORM后台代码

   public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // 进度发生变化之后的回调方法
        private void workder_ValueChanged(object sender, Business.ValueEventArgs e)
        {
            System.Windows.Forms.MethodInvoker invoker = () =>
                {
                    this.progressBar1.Value = e.Value;
                };

            if (this.progressBar1.InvokeRequired)
            {
                this.progressBar1.Invoke(invoker);
            }
            else
            {
                invoker();
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            // 禁用按钮
            this.button1.Enabled = false;

            // 实例化业务对象
            LongTime.Business.LongTimeWork workder = new Business.LongTimeWork();

            workder.ValueChanged += new Business.ValueChangedEventHandler(workder_ValueChanged);

            // 使用异步方式调用长时间的方法
            Action handler = new Action(workder.LongTimeMethod);
            handler.BeginInvoke(
                new AsyncCallback(this.AsyncCallback),
                handler
                );
        }

        // 结束异步操作
        private void AsyncCallback(IAsyncResult ar)
        {
            // 标准的处理步骤
            Action handler = ar.AsyncState as Action;
            handler.EndInvoke(ar);

            MessageBox.Show("工作完成!");

            System.Windows.Forms.MethodInvoker invoker = () =>
            {
                // 重新启用按钮
                this.button1.Enabled = true;
            };

            if (this.InvokeRequired)
            {
                this.Invoke(invoker);
            }
            else
            {
                invoker();
            }
        }

    }
View Code

 

http://download.csdn.net/detail/yekeyishuo/6485957

posted on 2013-11-01 10:53  YEKEYISHUO  阅读(482)  评论(0编辑  收藏  举报