Execute a Method Using the Thread Pool - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Thread

Description

Execute a Method Using the Thread Pool

Demo Code


using System;/*w  w w.j  a v a  2 s. c  o  m*/
using System.Threading;

class MainClass
    {
        private class MessageInfo
        {
            private int iterations;
            private string message;

            public MessageInfo(int iterations, string message)
            {
                this.iterations = iterations;
                this.message = message;
            }

            public int Iterations { get { return iterations; } }
            public string Message { get { return message; } }
        }
        public static void DisplayMessage(object state)
        {
            MessageInfo config = state as MessageInfo;

            if (config == null)
            {
                for (int count = 0; count < 3; count++)
                {
                    Console.WriteLine("A thread pool example.");
                    Thread.Sleep(1000);
                }

            }
            else
            {
                for (int count = 0; count < config.Iterations; count++)
                {
                    Console.WriteLine(config.Message);
                    Thread.Sleep(1000);
                }
            }
        }

        public static void Main()
        {
            ThreadPool.QueueUserWorkItem(DisplayMessage);
            MessageInfo info = new MessageInfo(5,"A thread pool example with arguments.");
            ThreadPool.SetMaxThreads(2, 2);
            ThreadPool.QueueUserWorkItem(DisplayMessage, info);
        }
    }

Related Tutorials