winform总结6=>线程和委托的关系

基础类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 线程和事件的关系
{
    public class DemoTest
    {
        public DemoTest(int time)
        {
            this.Time = time;
        }
        public delegate void DosomeThing(object sender,SetEventArgs setet);
        public event DosomeThing events;
        public int Time { get; set; }
        private string _t;
        public string T
        {
            get
            {
                return _t;
            }
            set 
            {
                this._t = value;
                SetEventArgs set = new SetEventArgs(this._t,this.Time);
                if (this.events != null)
                {
                    events(this, set);
                }
            }
        }
    }
    public class SetEventArgs : EventArgs
    {
        public int Time { get; set; }
        public string Name { get; set; }
        public SetEventArgs(string name,int time)
        {
            this.Name = name;
            this.Time = time;
        }
    }
}
View Code

测试:

 static void Main(string[] args)
        {
            DemoTest dt = new DemoTest(10000);
            dt.events += dt_events;
            dt.T = "副线程";
            Thread.Sleep(100);
            DemoTest df = new DemoTest(1);
            df.events += dt_events;
            df.T = "主线程";
            Console.ReadKey();
        }
        static void dt_events(object sender, SetEventArgs setet)
        {
            Thread.Sleep(setet.Time);
            Console.WriteLine(setet.Name);
        }

执行结果:先打印副线程然后打印主线程

 static void Main(string[] args)
        {
            Thread t = new Thread(() =>
            {
                DemoTest dt = new DemoTest(10000);
                dt.events += dt_events;
                dt.T = "副线程";
            });
            t.Start();
            Thread.Sleep(100);
            DemoTest df = new DemoTest(1);
            df.events += dt_events;
            df.T = "主线程";
            Console.ReadKey();
        }
        static void dt_events(object sender, SetEventArgs setet)
        {
            Thread.Sleep(setet.Time);
            Console.WriteLine(setet.Name);
        }

执行结果:先打印主线程再打印副线程

结论:将程序比作一棵树,那么类的实例,变量就是构成树的基本单元,主树干就是主线程,分支就是分线程,委托相当于绿叶,不同线程上边的委托相当于不同分支的绿叶,相同的叶子代表同一个委托链,任何输送到该叶子上边的养分阳光都会顺序吸收。生长的田地便是.netframework,田地之外就是操作系统。

 

欢迎拍砖!

 

 

posted @ 2017-01-19 14:50  FreeTimeWorker  阅读(662)  评论(0编辑  收藏  举报