02-使用委託與多線程實現窗體間傳值

一、主窗體代碼:多線程

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

二、子窗體代碼:ide

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

三、運行截圖:ui

相關文章
相關標籤/搜索