中断后代码仍在循环
Code is still looping after break
我有同一个应用程序的 3 个实例 运行。如果我让我的程序标记 1 个被杀死,它工作正常,2 个仍然 运行。当我标记另一个要被杀死时,它会杀死剩下的 2 个,而不是再杀死一个。如果我在 "break;" 之前放置一个消息框,它会正常工作,只会再杀死一个并留下一个 运行。但是如果没有消息框,当我试图杀死第二个实例时,它总是会同时杀死那个实例和第三个实例。知道为什么那里的消息框会使其正常工作吗?我假设某种类型的时间问题,但我不知道为什么,因为有 "break;".
foreach (WatcherScraperModel scraper in this.Scrapers.Except(scheduled.Where(x => x.Active)))
{
totalinstances = 0;
foreach (Process process in Process.GetProcesses())
{
try
{
if (process.MainModule.FileName == scraper.FileName)
{
// get instances already running
totalinstances++;
}
}
catch
{
// certain core processes cannot be accessed, don't worry about it
}
}
foreach (Process process in Process.GetProcesses())
{
try
{
// only kill an instance if there's too many running
if (process.MainModule.FileName == scraper.FileName && totalinstances > scheduled.Count(x => x.Active && x.FileName == scraper.FileName))
{
logger.DebugFormat("Killed {0} because it was not scheduled to be running", scraper.FileName);
process.Kill();
scraper.RestartRemaining = 0;
break;
}
}
catch
{
// certain core processes cannot be accessed, don't worry about it
}
}
}
查看 Process.Kill
的文档
The Kill method executes asynchronously. After calling the Kill method, call the WaitForExit method to wait for the process to exit, or check the HasExited property to determine if the process has exited.
如果您在 process.Kill();
之后添加 process.WaitForExit();
,那么下次您调用 Process.GetProcesses()
时,该进程将不再存在,从而使您的计数正确。这也解释了为什么添加消息框可以解决问题,因为这将使进程有时间在您继续外部 foreach
循环之前停止。
我有同一个应用程序的 3 个实例 运行。如果我让我的程序标记 1 个被杀死,它工作正常,2 个仍然 运行。当我标记另一个要被杀死时,它会杀死剩下的 2 个,而不是再杀死一个。如果我在 "break;" 之前放置一个消息框,它会正常工作,只会再杀死一个并留下一个 运行。但是如果没有消息框,当我试图杀死第二个实例时,它总是会同时杀死那个实例和第三个实例。知道为什么那里的消息框会使其正常工作吗?我假设某种类型的时间问题,但我不知道为什么,因为有 "break;".
foreach (WatcherScraperModel scraper in this.Scrapers.Except(scheduled.Where(x => x.Active)))
{
totalinstances = 0;
foreach (Process process in Process.GetProcesses())
{
try
{
if (process.MainModule.FileName == scraper.FileName)
{
// get instances already running
totalinstances++;
}
}
catch
{
// certain core processes cannot be accessed, don't worry about it
}
}
foreach (Process process in Process.GetProcesses())
{
try
{
// only kill an instance if there's too many running
if (process.MainModule.FileName == scraper.FileName && totalinstances > scheduled.Count(x => x.Active && x.FileName == scraper.FileName))
{
logger.DebugFormat("Killed {0} because it was not scheduled to be running", scraper.FileName);
process.Kill();
scraper.RestartRemaining = 0;
break;
}
}
catch
{
// certain core processes cannot be accessed, don't worry about it
}
}
}
查看 Process.Kill
The Kill method executes asynchronously. After calling the Kill method, call the WaitForExit method to wait for the process to exit, or check the HasExited property to determine if the process has exited.
如果您在 process.Kill();
之后添加 process.WaitForExit();
,那么下次您调用 Process.GetProcesses()
时,该进程将不再存在,从而使您的计数正确。这也解释了为什么添加消息框可以解决问题,因为这将使进程有时间在您继续外部 foreach
循环之前停止。