Anurag Malani

Anurag Malani

  • NA
  • 80
  • 34.4k

If CPU usage is 100% then close the all threads C#

Jun 16 2015 4:09 AM
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? 

Answers (2)