如何使用ThreadPool类

hud*_*uda 5 c#

namespace ThPool
{
    class Program
    {
        private static long val = 0;
        private static string obj = string.Empty;

        static void Main(string[] args)
        {
            Thread objThread1 = new Thread(new ThreadStart(IncrementValue));
            objThread1.Start();
            Thread objThread2 = new Thread(new ThreadStart(IncrementValue));
            objThread2.Start();
            objThread1.Join();
            objThread2.Join();

            Console.WriteLine("val=" + val + " however it should be " + (10000000 + 10000000));

            Console.ReadLine();
        }

        private static void IncrementValue()
        {
            for (int i = 0; i < 10000000; i++)
            {
                Monitor.Enter(obj);
                val++;
                Monitor.Exit(obj);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用ThreadPool类替换线程和监视器?

tui*_*oel 0

您可以使用BeginInvokeEndInvoke。它在幕后使用线程池,但更容易编程。看这里:

http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx