码迷,mamicode.com
首页 > 编程语言 > 详细

C# 跨线程访问控件的解决方法

时间:2015-10-02 00:12:04      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //方法一:不进行跨线程安全检查
            //System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread th1 = new Thread(new ThreadStart(CalNum));
            th1.Start();
        }

        private void CalNum()
        {
            //button1.Enabled = false;

            int result = 0;
            for (int i = 1; i < 100000000; i++)
            {
                result += i;
            }

            SetCalResult(result);

            //button1.Enabled = true;
        }

        //方法二:检查是否跨线程,然后将方法加入委托,调用委托
        public delegate void SetTextHandler(int result);
        private void SetCalResult(int result)
        {
            if (label2.InvokeRequired) //等待异步
            {
                SetTextHandler set = new SetTextHandler(SetCalResult);//委托的方法参数应和SetCalResult一致
                label2.Invoke(set, new object[] { result }); //此方法第二参数用于传入方法,代替形参result
            }
            else
            {
                label2.Text = result.ToString();
            }
        }
    }

 

C# 跨线程访问控件的解决方法

标签:

原文地址:http://www.cnblogs.com/luciakally/p/4851746.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!