Click here to Skip to main content
14,739,236 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi

Using TPL i am able to consume all cores of my machine, but sometimes the CPU usage reached to 100%. My question is how can we forcefully tell to program the terminate the all threads which are currently using and reset the task again.

Below is my program -

Parallel.For(0, loopCount, parallelOptions, loopno =>
{
    for (int i = 0; i < tDSInput.Tables[0].Rows.Count; i++)
    {
     
        ////////Here i want to chk the CPU usage (if cpu usage is > 95%) then stop all running threads else normal execution.  
         
        
        var locker = new object();
        Monitor.Enter(locker);
        try
        {
            var tasks = Task.Factory.StartNew(() => ABC(),TaskCreationOptions.LongRunning)
            .ContinueWith(t => DEF(), TaskContinuationOptions.ExecuteSynchronously)
            .ContinueWith(t => GHI(), TaskContinuationOptions.ExecuteSynchronously)
            .ContinueWith(t => JKL(), TaskContinuationOptions.ExecuteSynchronously)
            ....
            ....
            ....
            ....
            ....
            ....
            .ContinueWith(t => XYZ(), TaskContinuationOptions.ExecuteSynchronously)
            Task.WaitAll(tasks);
        }
        finally
        {
            Monitor.Exit(locker);
        }
    } 
} 


How do I do that?
Posted
Comments
virusstorm 16-Jun-15 11:40am
   
What you are attempting to do goes way beyond what the TPL (maybe even C# all together) was built for. The library is designed to scale it self across the available logical processors. The CPU usage will always spike to 100% when you use this library. The better question here is to ask, why do you need to stop all your tasks when the utilization hits 100%? Do you need to allow another process to take higher priority? Now we are taking task scheduling and process affinity.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900