02-使用委托与多线程实现窗体间传值

1、主窗体代码:

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

namespace _08委托与多线程实现窗体间传值
{
    public delegate void SetTextDel(string text);//声明

    public partial class MainFrm : Form
    {
        public MainFrm()
        {
            InitializeComponent();
            this.Text = Thread.CurrentThread.ManagedThreadId.ToString();//当前线程ID
            //线程间空间不能相互访问,允许其他线程来访问当前线程创建的 控件:Control
            //Control.CheckForIllegalCrossThreadCalls = false;//掩耳盗铃的方式
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //ChildFrm child = new ChildFrm();
            //child.setTextDel = SetText;//实例化
            //child.Show();

            //方法二:多线程
            Thread thread = new Thread(() =>
            {
                ChildFrm child = new ChildFrm();
                child.setTextDel = SetText;//实例化
                child.ShowDialog();
            });
            thread.Start();//要开启,告诉操作系统已经准备就绪,随时可以调用
        }

        private void SetText(string text)
        {
            //InvokeRequired 当线程执行到此的时候,校验一下txtMessage控件是哪个线程创建的。
            //如果是自己创建的InvokeRequired:fasle反之则为true
            if (this.txtMessage.InvokeRequired)//不是自己创建的
            {
                SetTextDel setTextDel = SetTextForOtherThread;
                this.Invoke(setTextDel,text);//Invoke(委托名,参数)
            }
            else
            {
                this.txtMessage.Text = text;
            }
        }

        private void SetTextForOtherThread(string text)
        {
            this.txtMessage.Text = text;
        }
    }
}
View Code

2、子窗体代码:

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

namespace _08委托与多线程实现窗体间传值
{
    public partial class ChildFrm : Form
    {
        public ChildFrm()
        {
            InitializeComponent();
            this.Text = Thread.CurrentThread.ManagedThreadId.ToString();
        }

        public SetTextDel setTextDel = null;//初始化

        private void btnSetMainTxt_Click(object sender, EventArgs e)
        {
            if (setTextDel != null)
            {
                setTextDel(this.txtSource.Text);//调用
            }
        }
    }
}
View Code

3、运行截图:

原文地址:https://www.cnblogs.com/zy-style/p/4335630.html