Limit number of processes in TPL

Source: Internet
Author: User

The MaxDegreeOfParallelism sets the maximum number of simultaneous threads that would be used for the Parallel.For() . It does not mean this only threads would ever be used.

Different threads can allocated from the ThreadPool during execution Parallel.For() of the, since ThreadPool threads is Specifi Cally designed to be reused.

The following program demonstrates. If you run it, you'll see that the total number of different threads being used can exceed 2, but the total number of thre Ads being used simultaneously never exceeds 2.

UsingSystem;UsingSystem.Collections.Concurrent;UsingSystem.Threading;UsingSystem.Threading.Tasks;NamespaceConsoleApp1{ Class Program { Static void Main() { ParallelOptionsPo= New ParallelOptions { Maxdegreeofparallelism = 2 }; VarActivethreads= New Concurrentdictionary<Int, bool> (); Parallel.For(0, 100,Po,X= {Activethreads[Thread.CurrentThread.Managedthreadid] = True; Console.WriteLine("Active Threads:" + String.Join(", ",Activethreads.Keys)); Threadsleep (200. Tryremove (thread. Currentthread. Managedthreadid, out  Unused console. Readline} }}    /span>                

Limit number of processes in TPL

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.