C # Multithreading for multi-core processors parallel.for and Parallel.ForEach

Source: Internet
Author: User

1. In. net4.0, there is a new class library: Task Parallel Library. It greatly simplifies parallel programming and is rich in content. Here are just some of the simplest

Parallel.For loops and Parallel.ForEach loops. They are located in the System.Threading.Tasks namespace. They are two methods that put iterations in parallel on different processors if the machine is a multiprocessor or multi-core processor, which can greatly improve performance.

2. Examples are calculated using Parallel.For, assigning and printing the array, and using Parallel.ForEach to calculate the length of each element of the string arrays, running the result:


3. Code:

using System;using System.Threading.Tasks; You must use this namespace namespace multithreaded methods for multicore processors Parallel.For and parallel.foreach{class program {static void Main (string[]            args) {Parallel.For (0,5,i=>console.writeline ("The square of {0} is {1}", I, i*i));            Console.WriteLine ();            const int maxvalues = 5;            Int[] Squares=new int[maxvalues];            Parallel.For (0, Maxvalues,i=>console.writeline (i*i));            Console.WriteLine (); string[] Squarsstr = new string[]{"We", "is", "the", "Kings", "of", "This", "beautiful", "World"            , "How", "Does", "You", "think"}; Parallel.ForEach (squarsstr, I = Console.WriteLine (string.            Format ("{0} has {1} letters", i,i.length));        Console.WriteLine (); }    }}

Multithreaded methods for multi-core processors for C # multithreading Parallel.For and Parallel.ForEach

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.