多线程之异步回调的运用

来源:互联网 发布:react webview js交互 编辑:程序博客网 时间:2024/06/05 09:11

应项目的技术需求,必须在某事件完毕后,根据返回结果执行相关业务逻辑,但前提是不允许出现UI假死,所以就想到了异步回调实现。

自身模拟了一下“轮循”。

以下为Winform案例源码 

        //状态值
        private bool isContinue=true;
        public Form3()
        {
            InitializeComponent();
        }

        //阻断主线程
        private void Stop(int i)
        {
            while (isContinue)
            {
                Thread.Sleep(i * 1000);
                MessageBox.Show("阻断执行完毕!");
            }
        }

        //执行线程阻断事件

        private void button1_Click(object sender, EventArgs e)
        {
            Action<int> act= new Action<int>(Stop);
            act.BeginInvoke(10, Doafter, "10");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("终止止断!");
            isContinue= false;
        }
        protected void Doafter(IAsyncResult iar)
        {
            MessageBox.Show("执行业务逻辑!");
        }