日期:2014-05-18 浏览次数:21319 次
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data.SqlClient;
using System.Data;
namespace ConApp
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int index = TASKCOUNT; --index >= 0; )
            {
                ThreadPool.QueueUserWorkItem(Run,index);
                Thread.Sleep(new Random(Guid.NewGuid().GetHashCode()).Next(100, 500));
            }
            wait.WaitOne();
            Console.WriteLine("任意键结束....");
            Console.ReadKey();
          
        }
        static ManualResetEvent wait = new ManualResetEvent(false);
        static int TASKCOUNT = 100;
        static void Run(object obj)
        {
            Thread.CurrentThread.Name = obj.ToString();
            Thread.Sleep(new Random(Guid.NewGuid().GetHashCode()).Next(4000, 5000));
            if (Interlocked.Decrement(ref TASKCOUNT) == 0)
            {
                wait.Set();
            }
            else
            {
                Console.WriteLine("完成{0}", obj);
            }
        }
    }   
}
------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data.SqlClient;
using System.Data;
namespace ConApp
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int index = TASKCOUNT; --index >= 0; )
            {
                ThreadPool.QueueUserWorkItem(Run, index);
                Thread.Sleep(new Random(Guid.NewGuid().GetHashCode()).Next(100, 500));
            }
            wait.WaitOne();
            Console.WriteLine("任意键结束....");
            Console.ReadKey();
        }
        static ManualResetEvent wait = new ManualResetEvent(false);
        static int TASKCOUNT = 100;
        static void Run(object obj)
        {
            Thread.CurrentThread.Name = obj.ToString();
            Thread.Sleep(new Random(Guid.NewGuid().GetHashCode()).Next(4000, 5000));
            if (Interlocked.Decrement(ref TASKCOUNT) == 0)
            {
                wait.Set();
            }
            else
            {
                Console.WriteLine("还有{0}个未完成", TASKCOUNT);
            }
        }
    }
}