首页 > 代码库 > winform 跨线程访问控件

winform 跨线程访问控件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        delegate void  DelShow(string strInput);
        DelShow delShow = null;
        public Form1()
        {
            InitializeComponent();
            delShow =new DelShow(MyShow);
            //Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            System.Threading.Thread t1 = new System.Threading.Thread(() => {
                if(this.InvokeRequired)
                {
                    #region 方式一
                    //this.Invoke(new Action<string>(s => { this.label1.Text = s; }),"bbb");
                    #endregion
                    #region 方式二
                    this.Invoke(delShow, "ccc");
                    #endregion
                }
                else
                {
                    this.label1.Text = "aaa";
                }
                
            });
            t1.IsBackground = true;
            t1.Start();
        }

        private void MyShow(string strInput)
        {
            this.label1.Text = strInput;
        }
    }
}

 

winform 跨线程访问控件