.NET 终止或结束进程

如何使用 C# 终止进程。

使用简单的方法终止.NET中的现有进程Process.Kill()。有一个可选参数 true 或 false,用于结束与要结束的进程相关的所有子进程。

了解如何创建流程

结束当前进程:

System.Diagnostics.Process.GetCurrentProcess().Kill(true);

结束当前计算机上所有名为"notepad"的进程:

static void KillAllNotepadProcesses()

{

System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName("notepad", "."); // use "." for this machine

foreach (var proc in procs)

proc.Kill(true);

}

要结束另一台计算机上名为"notepad"的所有进程:

static void KillAllNotepadProcesses()

{

System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName("notepad", "Machine-Name-or-IP-Address"); // enter the IP address or machine name

foreach (var proc in procs)

proc.Kill(true);

}

结束当前进程的所有其他实例:

static void KillAllOtherInstances()

{

System.Diagnostics.Process thisProc = System.Diagnostics.Process.GetCurrentProcess();

System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName(thisProc.ProcessName, "."); // use "." for this machine

foreach (var proc in procs)

if (proc.Id != thisProc.Id) // the process Id is unique across all processes while the process name can be common

proc.Kill(true);

}

完整的现实示例:

为了扩展上述代码片段,我们准备了以下代码。它使用强力算法来解决π,这对 CPU 来说非常耗电。因此,它会终止(杀死)自身的所有其他实例,以防止机器负担过重。编译此代码并尝试运行多个实例!

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading;

using System.Threading.Tasks;

namespace KillOtherInstancesAndSolvePI

{

class JobTask

{

public Task task { get; }

public int id { get; }

public double pi { get; set; }

public ulong iterations { get; set; }

public CancellationTokenSource CancelToken { get; }

public JobTask(int id)

{

this.id = id;

CancelToken = new CancellationTokenSource();

task = Task.Run(async () => // async not necessary in this example

{

var spaces = Environment.ProcessorCount.ToString().Length;

iterations = (ulong)new Random().Next() * 10;

Console.WriteLine("Started Job: {0, -" + spaces + "} Iterations: {1}", id, iterations);

pi = SolvePi(iterations, CancelToken);

Console.WriteLine("Job: {0, -" + spaces + "} ended with pi={1}", id, pi.ToString("0.00000000000000"));

}, CancelToken.Token);

}

static double SolvePi(ulong count, CancellationTokenSource cancel)

{

//π = 3.14159265358979323846264338327950288419...

//π = (4/1) - (4/3) + (4/5) - (4/7) + (4/9) - (4/11) + (4/13) - (4/15) + ...

//π = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 + ...)

double x = 1.0;

for (ulong i = 2; !cancel.IsCancellationRequested & (i < count); i++)

{

if ((i & 1) == 0)

x -= 1.0 / ((i << 1) - 1);

else

x += 1.0 / ((i << 1) - 1);

}

return 4.0 * x;

}

}

class Program

{

static void KillAllOtherInstances()

{

System.Diagnostics.Process thisProc = System.Diagnostics.Process.GetCurrentProcess();

System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName(thisProc.ProcessName, ".");

foreach (var proc in procs)

if (proc.Id != thisProc.Id)

proc.Kill(true);

}

static void Main(string[] args)

{

KillAllOtherInstances(); // end the other process before trying to solve PI

var jobTasks = new List<JobTask>();

Console.WriteLine("pi={0}", 3.1415926535897932384626433833.ToString("0.00000000000000"));

Console.WriteLine("Logical Processors: {0}", Environment.ProcessorCount);

Console.WriteLine("ENTER JOB NUMBER TO TERMINATE AT ANYTIME");

var spaces = Environment.ProcessorCount.ToString().Length;

int[] jobsIds = new int[Environment.ProcessorCount];

for (int i = 0; i < Environment.ProcessorCount; i++)

jobsIds[i] = i;

foreach(var jobId in jobsIds)

jobTasks.Add(new JobTask(jobId));

Thread.Sleep(250);

foreach (var j in jobTasks.OrderBy(j => j.iterations))

Console.WriteLine("Job: {0, -" + spaces + "} Iterations: {1}", j.id, j.iterations);

Task.Run(() => // create a task to terminate the app when all pi tasks are done

{

while (jobTasks.Where(j => j.task.IsCompleted == false).Count() > 0)

Thread.Sleep(250);

Environment.Exit(0);

});

while (jobTasks.Where(j => j.task.IsCompleted == false).Count() > 0) // look for a request to cancel a job from the user

{

var id = Console.ReadLine();

JobTask jt = jobTasks.Where(j => j.id.ToString() == id).FirstOrDefault();

if(jt != null)

jt.CancelToken.Cancel();

}

}

}

}

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
数据的世界013 小时前
.NET体系架构
架构·c#·.net
时光追逐者13 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 20 期(2025年1.1-1.5)
c#·.net·.netcore·微软技术
苏克贝塔13 小时前
c#版本、.net版本、visual studio版本之间的对应关系
c#·.net·visual studio
无所谓จุ๊บ1 天前
使用ML.NET进行对象检测
机器学习·.net
苏克贝塔1 天前
vs2022开发.net窗体应用开发环境安装配置以及程序发布详细教程
.net
三天不学习1 天前
【update 更新数据语法合集】.NET开源ORM框架 SqlSugar 系列
数据库·后端·c#·.net·orm·sqlsugar
步、步、为营2 天前
任务调度系统Quartz.net详解2-Scheduler、Calendar及Listener
服务器·.net
xk_hypothesis2 天前
.NET 在控制台或者桌面程序中使用依赖注入
.net
白白白白纸呀2 天前
ADO.NET知识总结6---SqlDataAdapter桥接器
开发语言·c#·.net