如何检查我的exe是否在后台进程中运行.如果不需要主动
本文关键字:运行 后台进程 如果 如果不 不需要 是否 何检查 检查 exe 我的 | 更新日期: 2023-09-27 18:16:37
我创建了一个windows服务,其中代码将每1秒执行一次
我的代码if (Process.GetProcessesByName("my_process").Length > 0)
{
writelog("Started uploading files");
upload_file();
writelog("Finished uploading files");
}
我正在检查进程是否已经使用GetProcessByName
运行。它不工作,因为每隔1秒,日志文件就会获得一个条目Started uploading files
所以我的日志文件将是
Started uploading files
Started uploading files
Started uploading files
Finished uploading files
Finished uploading files
Finished uploading files
我需要的是
Started uploading files
Finished uploading files
Started uploading files
Finished uploading files
Started uploading files
Finished uploading files
ie。没有完成第一个周期,服务就不应该进入流程。有没有办法做到这一点
您可以使用system . threading . mutex强制它作为单个实例应用程序。看看这个问题
可以使用互斥锁。要避免这个问题,可以这样使用:
private static object _sync = new object();
.....
if (Process.GetProcessesByName("my_process").Length > 0)
{
lock(_sync)//mutex here, so, only one thread will be able to launch this code.
{
if (Process.GetProcessesByName("my_process").Length > 0)
{
writelog("Started uploading files");
upload_file();
writelog("Finished uploading files");
}
}
}
这里的双重检查是为了性能。