C#有意循环。(低CPU使用率) https:/github.com0xyg3nProcessDaemon。

问题描述 投票:2回答:1

EDIT 谢谢大家提供的答案,这里是项目完成。


https:/github.com0xyg3nProcessDaemon。


如果有人提出多线程的解决方案,我想可能会更好。


我是C#的新手,我想问什么是最好的方法来创建一个有意的无限循环,而不破坏你的cpu使用率...... 更像是作为一个守护进程。

软件的概念是 。创建一个软件,能够确定一个特定的进程是否正在运行,以便执行一个代码块打破循环,并使循环再次。我知道如何扫描进程并进行循环等等,但我想要一些轻量级的软件。C#默认是作为单线程运行的,也许如果我把while(true)作为多线程,就能解决我的问题?

先谢谢大家了!

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.
        }
    }
}
c# loops while-loop
1个回答
2
投票

你可以把你的代码变成异步代码,然后添加一个Task.Delay(xx)来释放进程,同时等待。

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.
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.