zoukankan      html  css  js  c++  java
  • C# 跨线程访问控件的解决方法

    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();
                }
            }
        }
  • 相关阅读:
    浅谈动态开点线段树
    详解二叉查找树(BST)
    数组的随机打乱
    浅谈迭代加深搜索
    浅谈传递闭包问题
    详解权值线段树
    算法竞赛中桶的概念与应用
    NKOJ 1353 图形面积
    并查集 & 最小生成树详细讲解
    【线段树基础】NKOJ 1321 数列操作
  • 原文地址:https://www.cnblogs.com/luciakally/p/4851746.html
Copyright © 2011-2022 走看看