我创建了一个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
即。在完成第一个周期后,服务不应该进入该过程。 有没有办法实现这个
答案 0 :(得分:0)
您可以使用Sytem.Threading.Mutex将其强制为单实例应用程序。查看this question。
答案 1 :(得分:0)
您可以使用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");
}
}
}
此处仔细检查是为了表现。如果需要,您可以删除外部检查。