C#線程的啟動


在.net中為我們提供了兩種啟動線程的方式,一種是不帶參數的啟動方式,另一種是帶參數的啟動的方式。

1:不帶參數的啟動方式,可以使用ThreadStart來實例化Thread,ThreadStart是在.Net Framework 中已經定義好的委托,ThreadStart定義為:

public delegate void ThreadStart();

使用方法如下面的代碼:

 static void Main(string[] args)
        {
            Demo demo = new Demo();

            Thread t = new Thread(new ThreadStart(demo.Run));
            t.Name = "NoParameterThread";
            t.Start();
        }

 

   public class Demo
    {
        int interval = 1000;
        /// <summary>
        /// 不帶參數的啟動方法
        /// </summary>
        public void Run()
        {
            for (int i = 0; i < 10; i++)
            {
                DoSomething();
            }
        }

        private void DoSomething()
        {
            Console.WriteLine(string.Format("當前線程:{0},當前系統時間為:{1}", Thread.CurrentThread.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            Thread.Sleep(interval);
        }
}

2:帶參數的啟動方法,就要使用ParameterizedThreadStart委托來實例化Thread了,和ThreadStart一樣的是它也是線程啟動時要執行的方法,和ThreadStart不同的是,它在實例化時可以用一個帶有一個Object參數的方法作為構造函數的參數,而實例化ThreadStart時所用到的方法是沒有參數的。ParameterizedThreadStart定義為:

public delegate void ParameterizedThreadStart(object obj);

使用方法如下面的代碼:

 public class Demo
    {
        int interval = 1000;

        private void DoSomething()
        {
            Console.WriteLine(string.Format("當前線程:{0},當前系統時間為:{1}", Thread.CurrentThread.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            Thread.Sleep(interval);
        }

        /// <summary>
        /// 帶參數的啟動方法
        /// </summary>
        /// <param name="param"></param>
        public void Run(object param)
        {
            if (param == null)
                return;

            int.TryParse(param.ToString(), out interval);
            for (int i = 0; i < 10; i++)
            {
                DoSomething();
            }
        }

    }
static void Main(string[] args)
        {
            Demo demo = new Demo();

            Thread parameterThread = new Thread(new ParameterizedThreadStart(demo.Run));
            parameterThread.Name = "ParameterThread";
            parameterThread.Start(2000);
        }

3:在很多時候,我們遇到的情況是要傳遞多個參數,注意到ParameterizedThreadStart委托的參數類型是一個Object對象,為什么是Object這樣的參數呢?很簡單,因為在.net中Object是所有類型的基類。這樣我們可以聲明一個類,為這個類增加屬性,這些屬性也就是參數。

使用方法如下面的代碼:

 static void Main(string[] args)
        {
            Demo demo = new Demo();

            ThreadParamter p = new ThreadParamter(2000,100);
            Thread multiParameterThread = new Thread(new ParameterizedThreadStart(demo.CustomerParamterRun));
            multiParameterThread.Name = "MultiParameterThread";
            multiParameterThread.Start(p);
        }
 public class Demo
    {
        /// <summary>
        /// 帶多個參數的啟動方法
        /// </summary>
        /// <param name="param"></param>
        public void CustomerParamterRun(object param)
        {
            if (param == null)
                return;

            ThreadParamter p = param as ThreadParamter;
            if (p != null)
            {
                for (int i = 0; i < p.LoopCount; i++)
                {
                    Console.WriteLine(string.Format("當前線程:{0},當前系統時間為:{1}", Thread.CurrentThread.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                    Thread.Sleep(p.Interval);
                }
            }
        }
    }

    public class ThreadParamter
    {
        public int Interval { get; set; }
        public int LoopCount { get; set; }

        public ThreadParamter()
        { }

        public ThreadParamter(int interval, int loopCount)
        {
            this.Interval = interval;
            this.LoopCount = loopCount;
        }
    }

4:在遇到業務非常復雜的時候,上面寫法還是有問題,封裝不夠好,我們可以使用裝飾模式,對上面的代碼進行改進。這樣業務發生改變的時候,我們只需要修改核心的實現部分,調用的方法可以不用做任何修改,而且調用方法的代碼非常簡潔。

修改后的代碼如下:

 static void Main(string[] args)
        {
            DecoratorThread t = new DecoratorThread(new ThreadParamter(2000, 100));
            t.Start();
        }
 public class ThreadParamter
    {
        public int Interval { get; set; }
        public int LoopCount { get; set; }

        public ThreadParamter()
        { }

        public ThreadParamter(int interval, int loopCount)
        {
            this.Interval = interval;
            this.LoopCount = loopCount;
        }
    }

    /// <summary>
    /// 使用裝飾模式來實現多個參數的
    /// </summary>
    public class DecoratorThread
    {
        private ThreadParamter threadParamter;
        private Thread thread;


        public DecoratorThread(ThreadParamter threadParamter)
        {
            this.threadParamter = threadParamter;
            thread = new Thread(new ThreadStart(Run));
            thread.Name = "DecoratorThread";
        }

        public void Start()
        {
            if (thread != null)
            {
                thread.Start();
            }
        }

        private void Run()
        {
            for (int i = 0; i < threadParamter.LoopCount; i++)
            {
                Console.WriteLine(string.Format("當前線程:{0},當前系統時間為:{1}", Thread.CurrentThread.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                Thread.Sleep(threadParamter.Interval);
            }
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM