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();
                }
            }
        }
  • 相关阅读:
    appium 元素定位方法
    Mac 使用MuMu模拟器调试
    渗透测试工具Drozer安装使用(Mac)
    渗透测试工具Drozer安装使用(Windows)
    python虚拟环境搭建
    HDU 6900 Residual Polynomial【分治 NTT】
    CF 1405E Fixed Point Removal【线段树上二分】
    Educational Codeforces Round 41
    Educational Codeforces Round 39
    Educational Codeforces Round 36
  • 原文地址:https://www.cnblogs.com/luciakally/p/4851746.html
Copyright © 2011-2022 走看看