using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ScanExtendDemo
{
    class CpuEater
    {
        //This should be more than the cores/cpu threads.
        const int NumThreads = 8;

        private Thread[] m_threads = new Thread[NumThreads];

        private bool m_run = false;

        public CpuEater()
        {

        }

        public bool IsRunning
        {
            get { return m_run; }
        }

        public void Run()
        {
            Stop();

            Thread.CurrentThread.Priority = ThreadPriority.Highest;

            m_run = true;
            for (int i = 0; i < m_threads.Length; i++)
            {
                m_threads[i] = new Thread(StartThread);
                m_threads[i].Priority = ThreadPriority.AboveNormal;
                m_threads[i].Start(this);
            }

        }

        public void Stop()
        {
            if (!m_run)
                return;

            m_run = false;
            foreach(var thread in m_threads)
            {
                thread.Join();
            }

            Thread.CurrentThread.Priority = ThreadPriority.Normal;
        }

        private static void StartThread(object thatObj)
        {
            CpuEater that = (CpuEater)thatObj;
            that.DoCpuWork();
        }

        private void DoCpuWork()
        {
            double total = 0;
            while(m_run)
            {

                var rnd = new Random();
                var num = rnd.Next();
                var res = Math.Sqrt(Math.Sqrt(num));
                total += res;
            }
        }

    }
}
