首页 > 技术文章 > WinForm多线程编程简单Demo

zhuji 2016-03-01 15:01 原文

需要搭建一个可以监控报告生成的CS(WinForm)工具,即CS不断Run,执行获取数据生成报告,经过研究和实践,选择了使用"WinForm多线程编程"的解决方案.当然参考了园中相关文章自己搞的一个Demo.

PS:由于报告生成非常耗费资源,使用单线程编程模式, 监控信息根本无法信息无法及时在RichText显示.

    public partial class Form1 : Form
    {

        private CancellationTokenSource _cts;

        private int testNum = 1;

        public Form1()
        {
            InitializeComponent();

        }


        private void CreateRPT(CancellationToken ct)
        {
            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }
                //Invoke方法用于获得创建lbl_Status的线程所在的上下文
                this.Invoke(new Action(() => richTextBox1.Text = testNum.ToString()));
                testNum += 1;
                Thread.Sleep(2000);
            }
        }

        private void btn_Count_Click(object sender, EventArgs e)
        {
            _cts = new CancellationTokenSource();
            ThreadPool.QueueUserWorkItem(state => CreateRPT( _cts.Token ));
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            if (_cts != null)
                _cts.Cancel();
        }

    }

 又看到一个风格

       private void CreateRPT(CancellationToken ct)
        {
            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }
                //Invoke方法用于获得创建lbl_Status的线程所在的上下文
                //this.Invoke(new Action(() => richTextBox1.Text = testNum.ToString()));
                ViewMsg(testNum.ToString());
                testNum += 1;
                Thread.Sleep(2000);
            }
        }

        private void ViewMsg(string msg)
        {

            /*

            control.Invoke(new SetControlTextDelegate((ct, v) => { ct.Text = v; }), new object[] { control, value });
             =>
             control.Invoke(new Action<Control, string>((ct, v) => { ct.Text = v; }), new object[] { control, value });

            */
            this.richTextBox1.Invoke(new Action<RichTextBox, string>((ct, v) => { ct.AppendText(v); ct.Refresh(); }),new object[] { this.richTextBox1, msg });
            this.richTextBox1.Invoke(new Action<string>((v) => { this.richTextBox1.AppendText(v); this.richTextBox1.Refresh(); }),msg);
        }

 

推荐阅读