新文章

2012年8月24日 星期五

[C#]ThreadPool 範例

最近開始接觸Thread,多點練習幫助自己學習


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

namespace AsynchronousSample
{
    //Threadpool Sample
    class Sample1
    {
        static void Main(string[] args)
        {
            ThreadPool.QueueUserWorkItem(Counter);
            ThreadPool.QueueUserWorkItem(Counter,"t1");
            Console.WriteLine("[The main process id:{0}]\tStart the main process", Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(500);
            Console.WriteLine("The main process left.");
            Console.ReadLine();
        }

        public static void Counter(object state)
        {
            Console.WriteLine("Start counting from 1 to 10 :");
            Console.WriteLine("receive args:{0}", state);
            for (int counter = 0; counter < 10; counter++)
            {
                if (null == state)
                {
                    Console.WriteLine("[Process ID = {0}] {1}", Thread.CurrentThread.ManagedThreadId, counter);
                }
                else
                {
                    Console.WriteLine("[Process ID = {0}] {1}", Thread.CurrentThread.ManagedThreadId, state);
                }
                Thread.Sleep(100);
            }
        }

    }
}

沒有留言:

張貼留言