2 wangdbtocsv WangDbtoCsv 于 2014.12.18 14:30 提问

为什么在每分钟执行一次的任务计划中不能强制终止,要等待执行结束

代码如下:
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"));
    }
}

}

4个回答

feiyun0112
feiyun0112   Rxr 2014.12.18 14:43

应该是不能“自杀”,你用其他进程来杀看看

WangDbtoCsv
WangDbtoCsv   2014.12.18 15:10

用鼠标双击程序执行的话,可以终止程序执行.用任务计划需要等待程序结束.

caozhy
caozhy   Ds   Rxr 2014.12.20 04:59
    foreach (Process p in killprocess2)
    {
            p.Kill();
    }
调试下,貌似是没有找到进程,这个没有执行
WangDbtoCsv
WangDbtoCsv   2014.12.26 10:34

谢谢
foreach (Process p in killprocess2)
{
p.Kill();
}
是在有CappW.vshost.exe 的情况下,执行杀死动作的。也可以没有。关键是为何等待,原先的CappW.exe 执行完毕。而从外部激活就可以。新旧process
ID是不一样的。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!