我是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.
}
}
}
你可以把你的代码变成异步代码,然后添加一个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.
}
}
}