.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();

}

}

}

}

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

相关推荐
步步为营DotNet9 小时前
5-2EFCore性能优化
数据库·性能优化·.net
SEO-狼术21 小时前
.Net Forms Resize Crack
.net
许泽宇的技术分享21 小时前
Text2Sql.Net架构深度解析:从自然语言到SQL的智能转换之道
sql·架构·.net
追逐时光者1 天前
一款基于 .NET 开源美观、功能丰富的串口调试工具
.net
瀚高PG实验室1 天前
外网获取瀚高.NET驱动dll方法和使用案例
.net·瀚高数据库
2501_926227942 天前
.Net程序员就业现状以及学习路线图(四)
学习·.net
喵叔哟2 天前
54.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--新增功能--实现手机邮箱注册
微服务·智能手机·.net
喵叔哟2 天前
52.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--解决客户端调用接口404问题
微服务·架构·.net