问题描述
- 为什么在每分钟执行一次的任务计划中不能强制终止,要等待执行结束
-
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
//using System.Management;
//using System.Management.Instrumentation;
namespace CappW
{
class Program
{
///
/// Kill a process, and all of its children.
///
/// Process ID.
/* private static void KillProcessAndChildren(int pid)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
try
{
Process proc = Process.GetProcessById(pid);
proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}
*/
public static void KillProc(string procname,int myid)
{
Process[] allProcess = Process.GetProcesses();
foreach (Process p in allProcess)
{
System.Console.WriteLine(p.ToString()+"->"+p.Id);
}
Process[] killprocess = Process.GetProcessesByName(procname);
foreach (Process p in killprocess)
{
if (myid != p.Id)
{
// KillProcessAndChildren(p.Id);
p.Kill();} } //CappW.vshost Process[] killprocess2 = Process.GetProcessesByName(procname + ".vshost"); foreach (Process p in killprocess2) { p.Kill(); } } static void Main(string[] args) { string knme = "CappW"; Random ran = new Random(); int aa = ran.Next(50, 80); Process p2=Process.GetCurrentProcess(); int myid = p2.Id; System.Console.WriteLine("starttime:" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")); KillProc(knme,myid); for (int i = 0; i < 10; i++) { Thread.Sleep(aa * 200); } System.Console.WriteLine("endtime:" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")); } }
}
解决方案
应该是不能“自杀”,你用其他进程来杀看看
解决方案二:
用鼠标双击程序执行的话,可以终止程序执行.用任务计划需要等待程序结束.
解决方案三:
foreach (Process p in killprocess2)
{
p.Kill();
}
调试下,貌似是没有找到进程,这个没有执行
解决方案四:
谢谢
foreach (Process p in killprocess2)
{
p.Kill();
}
是在有CappW.vshost.exe 的情况下,执行杀死动作的。也可以没有。关键是为何等待,原先的CappW.exe 执行完毕。而从外部激活就可以。新旧process
ID是不一样的。
时间: 2024-12-02 13:20:11