C# Intentional Loop. (Low CPU Usage)

Viewed 350

EDIT: Thanks everyone for providing their answers here is the project completed.


https://github.com/0xyg3n/ProcessDaemon/


If someone comes up with multi thread solution that might work better i think.


I am new in C# and i would like to ask what is the best way to create an intentional infinite loop that does not destroy your cpu usage... More like as a daemon.

Concept of Software is : Create a software that is able to determine if a specific process is running in order to execute a block of code break the loop and make the loop again. I know how to scan the processes and make the loop etc etc but i want something lightweight. C# by default is running as single thread , maybe if i did the while(true) as multi threaded that would solve my problem???

Thanks in advance!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace ProcessDaemon
{
    class Program
    {
        static void Main(string[] args)
        {

            void CP()
            {
                Process[] pname = Process.GetProcessesByName("notepad");
                if (pname.Length == 0)
                {
                    //if not running
                }
                else
                {
                    //if running
                    //break the code
                    //retry loop
                }
            }


            void cronCP()
            {
                while(true)
                {
                    CP();
                }
            }

            cronCP(); //scan the processes infinitely.
        }
    }
}
1 Answers

You can turn your code into async code and then add a Task.Delay(xx) to release the process while awaiting

namespace ProcessDaemon
{
    class Program
    {
        static async Task Main(string[] args)
        {

            void CP()
            {
                Process[] pname = Process.GetProcessesByName("notepad");
                if (pname.Length == 0)
                {
                    //if not running
                }
                else
                {
                    //if running
                    //break the code
                    //retry loop
                }
            }


            async Task cronCP()
            {
                while (true)
                {
                    await Task.Delay(1000);
                    CP();
                }
            }

            await cronCP(); //scan the processes infinitely.
        }
    }
}
Related