C# 进程的任务管理

2023-12-17 20:41:02


try
{
//进程任务调度
using (Process myProcess = new Process())
{
List<Task> TaskList = new List<Task>();
Task task1 = new Task(() =>
{
? ? Task.Delay(TimeSpan.FromSeconds(4));
? ? var processName = "C:\\Users\\shil\\AppData\\Local\\Postman\\Postman.exe";
? ? RunProcess(processName);
});
Task task2 = new Task(() =>
{
? ? Task.Delay(TimeSpan.FromSeconds(3));
? ? var processName = "C:\\Program Files (x86)\\Tencent\\QQ\\Bin\\QQScLauncher.exe";
? ? RunProcess(processName);
});
Task task3 = new Task(() =>
{
? ? Thread.Sleep(200);
? ? Console.WriteLine("task3");
});
Task task4 = new Task(() =>
{
? ? Thread.Sleep(100);
? ? Console.WriteLine("task4");
});

TaskList.Add(task1);
TaskList.Add(task2);
TaskList.Add(task3);
TaskList.Add(task4);

foreach (Task task in TaskList)
{
? ? task.Start();
? ? task.Wait();
}


? ? ? ? //终止
? ? ? ? //KillProcess("Postman");
? ? }
}
catch (Exception e)
{
? ? Console.WriteLine(e.Message);
}

void RunProcess(string processName)
{
? ? Process myProcess = new Process();
? ? //进程创建,执行?
? ? myProcess.StartInfo.UseShellExecute = false;
? ? // You can start any process, HelloWorld is a do-nothing example.
? ? myProcess.StartInfo.FileName = processName;
? ? myProcess.StartInfo.CreateNoWindow = true;
? ? myProcess.Start();

}


void KillProcess(string processName)
{
? ? //进程关闭
? ? Process[] myproc = Process.GetProcesses();
? ? foreach (Process item in myproc)
? ? {
? ? ? ? if (item.ProcessName == processName)
? ? ? ? {
? ? ? ? ? ? item.Kill();
? ? ? ? ? ? item.WaitForExit(); // possibly with a timeout
? ? ? ? }
? ? }

}

文章来源:https://blog.csdn.net/qq_34417247/article/details/135049020
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。