Skip to main content

Running parallel tasks using ThreadPool.QueueUserWorkItem Method in .NET 3.5

Sometimes we need to run tasks in parallel so that performance of any application can be improved. Here is the sample function to run task in parallel using ThreadPool.QueueUserWorkItem. These parallel task will be added to Queue and as soon as thread is available in thread pool task will be executed. So number of tasks running in parallel depends upon the number of threads available in threadpool. So, in case if system have multiple processors then more threads will be available in threadpool and more tasks can run in parallel.

C# Function to run tasks in parallel -


          /// <summary>
        /// Function to Executes a set of methods or tasks in parallel. The results
        /// from each task or method in an array will be returned when all threads 
        ///  have completed.No parameter and return value must not be provided with task or methods
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public static void ExecuteParallel (params Action[] tasks)
        {
            // Initialize the reset events to keep track of completed threads
            ManualResetEvent [] resetEvents new ManualResetEvent [tasks. Length];

            // Launch each method in it's own thread
            for (int i = 0; i tasks . Lengthi ++)
            {
                resetEvents [i ] = new ManualResetEvent (false );
                ThreadPool .QueueUserWorkItem ( new WaitCallback ((object index) =>
                {
                    int taskIndex = ( int) index ;

                    // Execute the method
                    tasks [taskIndex ]();

                    // Tell the calling thread that we're done
                    resetEvents [taskIndex ]. Set();
                }), i );
            }

            // Wait for all threads to execute
            WaitHandle .WaitAll ( resetEvents);
        }
  

               //Sample use

          ExecuteParallel (() =>
          {
               CalculateArea (),
               CalculateDistance (),
               CalculateTime ()
          });

Comments

  1. I get error like ";" expected... am i calling this correctly ?? i am using VS2015 ExecuteParallel(() => {
    getlogmod(),
    getrolemod()
    });

    ReplyDelete
  2. class Program
    {
    static int distance =100;
    static int time = 100;

    static int speed = 10;
    static int length = 10;
    static int breath = 9;


    static void Main(string[] args)
    {
    ExecuteParallel(() =>
    {
    CalculateArea();
    CalculateDistance();
    CalculateTime();
    });

    Console.WriteLine("Hello World!");

    Console.ReadLine();
    }

    private static void CalculateTime()
    {
    Console.WriteLine("time " + distance / speed);
    }

    private static void CalculateDistance()
    {
    Console.WriteLine("Distance="+ time*speed);
    }

    private static void CalculateArea()
    {
    Console.WriteLine("Area ="+ length*breath);
    }


    public static void ExecuteParallel(params Action[] tasks)
    {
    // Initialize the reset events to keep track of completed threads
    ManualResetEvent[] resetEvents = new ManualResetEvent[tasks.Length];

    // Launch each method in it's own thread
    for (int i = 0; i < tasks.Length; i++)
    {
    resetEvents[i] = new ManualResetEvent(false);
    ThreadPool.QueueUserWorkItem(new WaitCallback((object index) =>
    {
    int taskIndex = (int)index;

    // Execute the method
    tasks[taskIndex]();

    // Tell the calling thread that we're done
    resetEvents[taskIndex].Set();
    }), i);
    }

    // Wait for all threads to execute
    WaitHandle.WaitAll(resetEvents);
    }


    //Sample use


    }

    Implementation

    ReplyDelete

Post a Comment

Popular posts from this blog

Show Image on canvas HTML5

Here is the sample code to select image from system and display it on html5 canvas and javascript: <input type= "file" id= "selectedImage" /> <canvas id= "myCanvas" width= "500" height= "500" > </canvas> Javascript code: $( "#selectedImage" ).change( function (e) { var URL = window .URL; var url = URL.createObjectURL(e.target.files[ 0 ]); img.src = url; img.onload = function () { var canvas = document .getElementById( "myCanvas" ); var ctx = canvas.getContext( "2d" ); var imgSize = calculateAspectRatioFit(img.width, img.height, canvas.clientWidth, canvas.clientHeight); ctx.clearRect( 0 , 0 , canvas.width, canvas.height); ctx.drawImage(img, 0 , 0 , imgSize.width, imgSize.height); } }); function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) { var ratio = Math .min(maxWi

Pass byte array from C# to C++ and vice-versa

Pass byte array from C# to C++                           If you want to pass a byte array to native DLL as parameter, you can use the Intptr to do this, please check the demo below. /C++ API code: TestDLL_API void TestArrayPara (BYTE * pArray, int nSize) { for ( int i= 0 ; i<nSize; i++) printf( "%d\n" , pArray[i]); } //C# code: class TestClass { [DllImport(@"TestDll.dll")] public static extern void TestArrayPara (IntPtr pArray, int nSize); public static void Test () { byte [] array = new byte [ 16 ]; for ( int i = 0 ; i < 16 ; i++) { array[i] = ( byte )(i + 97 ); } int size = Marshal.SizeOf(array[ 0 ]) * array.Length; IntPtr pnt = Marshal.AllocHGlobal(size); try { // Copy the array to unmanaged memory. Marshal.Copy(array, 0 , pnt, array

Display Tooltip for Combo Box item C#.NET Winforms

In windows form combo box control sometimes while adidng items dynamically we have items whose width is greater than width of combox box control. In this case for making UI more user friendly we can show tooltip over such item. Here is the sample C# code to display such tooltip:  Add a Tooltip control on the form.  Add following code : this . combo_box1 . DropDownStyle = System . Windows . Forms . ComboBoxStyle . DropDownList; this . combo_box1 . DrawMode = DrawMode . OwnerDrawFixed; this . combo_box1 . DrawItem += new DrawItemEventHandler(combo_box1_DrawItem); this . combo_box1 . DropDownClosed += new EventHandler(combo_box1_DropDownClosed); this . combo_box1 . MouseLeave += new EventHandler(combo_box1_Leave); void combo_box1_DrawItem( object sender, DrawItemEventArgs e) { if (e . Index < 0 ) { return ; } string text = combo_box1 . GetItemText(combo_box1 . Items[e . Index