[2014-9-15]异步委托线程高级

昨天悲剧,帮别人调代码,愣没调出来。还没时间写博文了。 忧桑...

昨天的今天写吧,今天也没学,就上了一天的课、

1 首先窗口间数据进行传递。也就是父窗口与子窗口数据进行传递。

用委托实现

①,在同一命名控件下定义委托。

②,在子窗口创建委托实例。

③,在父窗口创建子窗口对象,传递委托方法。

 public delegate void SetString(string str);
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Text = Thread.CurrentThread.ManagedThreadId.ToString();
            //允许其他线程来访问
           // Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnMain_Click(object sender, EventArgs e)
        {
            FChild fChild = new FChild();
            fChild.SetStr = new SetString(set);
            fChild.Show();
        }
        private void set(string str)

        {

             this.txtMain.Text=str;
         }
    }

子窗口:

        public FChild()
        {
            InitializeComponent();
            this.Text = Thread.CurrentThread.ManagedThreadId.ToString();
        }
        public SetString SetStr;

        private void btnChild_Click(object sender, EventArgs e)
        {
            SetStr(this.txtChild.Text);
        }

用多线程实现:

   线程之间传递在不同窗口之间不能传递,也就是允许其他线程来访问 当前线程创建的控件

  Control.CheckForIllegalCrossThreadCalls = false;//不推荐这个方法

 使用Invoke()方法

public delegate void SetTextDel(string txt);

    public partial class MainFrm : Form
    {
        private SetTextDel MySetCotrolTxt4OtherThreadDel;

        public MainFrm()
        {
            InitializeComponent();

            this.Text = Thread.CurrentThread.ManagedThreadId +"";

            //允许其他线程来访问 当前线程创建的 控件:Control
            //掩耳盗铃
            //Control.CheckForIllegalCrossThreadCalls = false;

            MySetCotrolTxt4OtherThreadDel = new SetTextDel(this.SetText4OtherThread);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //ChildFrm frm = new ChildFrm();
            //frm._SetTextDel = new SetTextDel(SetText);
            //frm.Show();

            Thread thread = new Thread(()=>
                                           {
                                               ChildFrm frm = new ChildFrm();
                                               frm._SetTextDel = new SetTextDel(SetText);
                                               frm.ShowDialog();
                                           });
            thread.Start();
        }

        public void SetText(string txt)
        {
            //InvokeRequired 当线程执行到此的时候,校验一下txtMessage控件是哪个线程创建的。如果是自己创建的InvokeRequired:fasle反之则为true
            if(this.txtMessage.InvokeRequired)
            {
                this.Invoke(MySetCotrolTxt4OtherThreadDel, txt);
            }
            else
            {
                this.txtMessage.Text = txt;  
            } 
        }

        public void SetText4OtherThread(string strTxt)
        {
            this.txtMessage.Text = strTxt;
        }
    }

posted @ 2014-09-15 20:36  Bparadise  阅读(96)  评论(0编辑  收藏  举报