C#通过“委托和事件”的方式实现进程监控并与“普通方式”对比
今天重新学习了一下观察者模式,对我的思路产生了启发。进程监控程序之前写过几个,这回换一种思路,改用委托和事件来实现。我已经用序号将关键的几步标注,方便大家理顺思路。代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace ProcessMonitor
{
public partial class ProcessMonitorForm : Form
{
public ProcessMonitorForm()
{
InitializeComponent();
//Add the processes into the combox.
var processes = Process.GetProcesses();
foreach (var process in processes)
{
processComboBox.Items.Add(process.ProcessName.ToString());
}
}
//The method that starts the monitor.
private void startButton_Click(object sender, EventArgs e)
{
//4.Register the monitor.
ProcessExit += new ProcessMonitor(ProExit);
//Start the check.
CheckProcess();
}
//The mothod that checks the process.
private void CheckProcess()
{
bool flag = true;
do
{
var processes = Process.GetProcesses();
int count = ;
foreach (var process in processes)
{
if (string.Compare(process.ProcessName, processComboBox.Text, true) == )
{
count++;
}
}
if (count == )
{
//5.The event appears.
ProcessExit(this, new EventArgs());
flag = false;
}
} while (flag);
}
//1.The delegate that monitor the process.
public delegate void ProcessMonitor(object sender, EventArgs strEventArg);
//2.The event that encapsulates the delegate.
public event ProcessMonitor ProcessExit;
//3.The method that the delegate calls.
private void ProExit(object sender, EventArgs strEventArg)
{
MessageBox.Show("The target process has been dispeared.");
}
}
}
为了不长篇累牍,效果只是简单实现,实际工作中可以随便扩展(选择进程,点击Start按钮进行监控。):
目标程序消失后弹出提示:

再附上一个脱去委托和事件的版本,代码如下(实现效果相同):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace ProcessMonitor
{
public partial class ProcessMonitorForm : Form
{
public ProcessMonitorForm()
{
InitializeComponent();
//Add the processes into the combox.
var processes = Process.GetProcesses();
foreach (var process in processes)
{
processComboBox.Items.Add(process.ProcessName.ToString());
}
}
//The method that starts the monitor.
private void startButton_Click(object sender, EventArgs e)
{
//Start the check.
CheckProcess();
}
//The mothod that checks the process.
private void CheckProcess()
{
bool flag = true;
do
{
var processes = Process.GetProcesses();
int count = ;
foreach (var process in processes)
{
if (string.Compare(process.ProcessName, processComboBox.Text, true) == )
{
count++;
}
}
if (count == )
{
ProExit();
flag = false;
}
} while (flag);
}
private void ProExit()
{
MessageBox.Show("The target process has been dispeared.");
}
}
}
如果用Action内置委托类型来完成的话就更方便了,代码如下(已经用序号标注关键步骤):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace ProcessMonitor
{
public partial class ProcessMonitorForm : Form
{
public ProcessMonitorForm()
{
InitializeComponent();
//Add the processes into the combox.
var processes = Process.GetProcesses();
foreach (var process in processes)
{
processComboBox.Items.Add(process.ProcessName.ToString());
}
}
//The method that starts the monitor.
private void startButton_Click(object sender, EventArgs e)
{
//Start the check.
CheckProcess();
}
//The mothod that checks the process.
private void CheckProcess()
{
//1.Define the action.
Action<string> processExit = s => MessageBox.Show(s);
bool flag = true;
do
{
var processes = Process.GetProcesses();
int count = ;
foreach (var process in processes)
{
if (string.Compare(process.ProcessName, processComboBox.Text, true) == )
{
count++;
}
}
if (count == )
{
//2.Active the action.
processExit("The target process has been dispeared.");
flag = false;
}
} while (flag);
}
}
}
脱去委托和事件的版本代码量明显比用委托和事件的代码量少了,为什么我们还要选择用委托和事件来做这件事呢?到底什么情况下,更适合用委托和事件的方式来完成?书中说,委托可以提高方法扩展性,没错,是这样的,说白了就是因为更高级!个人意见哈,在代码量少,以后不需要扩展方法的情况下,用不着用委托和事件的方式去完成,直接调用方法就好了。如果我说错了,欢迎指正我。
利用C#6.0中的语法糖扩展方法来替代foreach循环,代码量将更少。代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace ProcessMonitor
{
public partial class ProcessMonitorForm : Form
{
public ProcessMonitorForm()
{
InitializeComponent();
//Add the processes into the combox.
var processes = Process.GetProcesses();
foreach (var process in processes)
{
processComboBox.Items.Add(process.ProcessName.ToString());
}
}
//The method that starts the monitor.
private void startButton_Click(object sender, EventArgs e)
{
//Start the check.
CheckProcess();
}
//The mothod that checks the process.
private void CheckProcess()
{
//1.Define the action.
Action<string> processExit = s => MessageBox.Show(s);
bool flag = true;
do
{
var processes = Process.GetProcesses();
var countVar = processes.Where(i => i.ProcessName == processComboBox.Text);
if (countVar.Count() == )
{
//2.Active the action.
processExit("The target process has been dispeared.");
flag = false;
}
} while (flag);
}
}
}
C#通过“委托和事件”的方式实现进程监控并与“普通方式”对比的更多相关文章
- C#窗体间常用的几种传值方式、以及委托与事件的详细介绍
窗体间的传值,最好使用委托方式传值,开始之前,我们先来说一下委托与事件的关系. 委托:是一个类. 事件:是委托类型的一个特殊实例,只能在类的内部触发执行. 首先创建2个窗体,这里我们以form1为发送 ...
- .NET面试题系列[7] - 委托与事件
委托和事件 委托在C#中具有无比重要的地位. C#中的委托可以说俯拾即是,从LINQ中的lambda表达式到(包括但不限于)winform,wpf中的各种事件都有着委托的身影.C#中如果没有了事件,那 ...
- .NET基础拾遗(4)委托、事件、反射与特性
Index : (1)类型语法.内存管理和垃圾回收基础 (2)面向对象的实现和异常的处理基础 (3)字符串.集合与流 (4)委托.事件.反射与特性 (5)多线程开发基础 (6)ADO.NET与数据库开 ...
- [转载]C#深入分析委托与事件
原文出处: 作者:风尘浪子 原文链接:http://www.cnblogs.com/leslies2/archive/2012/03/22/2389318.html 同类链接:http://www.c ...
- [转载]C#委托和事件(Delegate、Event、EventHandler、EventArgs)
原文链接:http://blog.csdn.net/zwj7612356/article/details/8272520 14.1.委托 当要把方法作为实参传送给其他方法的形参时,形参需要使用委托.委 ...
- C#之委托与事件
委托与事件 废话一堆:网上关于委托.事件的文章有很多,一千个哈姆雷特就有一千个莎士比亚,以下内容均是本人个人见解. 1. 委托 1.1 委托的使用 这一小章来学习一下怎么简单的使用委托,了解一些基本的 ...
- C# 关于委托和事件的妙文:通过一个例子详细介绍委托和事件的作用;Observer模式简介
委托和事件在 .Net Framework中的应用非常广泛,然而,较好地理解委托和事件对很多接触C#时间不长的人来说并不容易.它们就像是一道槛儿,过了这个槛的人,觉得真是太容易了,而没有过去的人每次见 ...
- C#知识体系(二)用案例来理解委托与事件
上一篇博客讲到了LinQ和lambda的常用方法 还有很多我们未知但c#设计团队已经为我们封装好的类和方法.随着我们不断的熟悉C#语言,渐渐的就会接触到其他的知识点,委托.事件.反射.线程.同步,异步 ...
- [转]大白话系列之C#委托与事件讲解(三)
本文转自:http://www.cnblogs.com/wudiwushen/archive/2010/04/21/1717378.html [我希望大家在看完文章的时候,多做做练习,自己也可以想个场 ...
随机推荐
- assert语句(assert用来判断语句的真假)
# -*- coding: utf-8 -*- #python 27 #xiaodeng #Python学习手册 868 #assert语句(assert用来判断语句的真假) #案例 mylist=[ ...
- topas解析(AIX)
topas解析 topas 的显示信息和解析 (1) topas monitor for host:localhost topas监控的主机名称localhost tue Aug 14 14:1 ...
- Android API之android.provider.ContactsContract.RawContacts
android.provider.ContactsContract.RawContacts Constants for the raw contacts table, which contains o ...
- 如何显示Firefox插件(Plugins)的完整路径并删除
在Firefox里面,插件firefox只提供禁用选项,无法直接卸载. 要卸载插件,可以按照下面的步骤: 1.在地址栏内,输入 about:config,回车:在过滤器那一栏输入 plugin.exp ...
- 一般web典型的项目目录结构
本文转自:http://blog.sina.com.cn/s/blog_4758a28b0100l3lp.html WebRoot- -common (系统框架公用jsp 如foote ...
- Google地图之OverlayView使用(自定义叠加层)
Google Maps API 第 3 版提供了用于创建自定义叠加层的 OverlayView 类.OverlayView 是一个基类,提供了您在创建叠加层时必须实现的若干方法.该类还提供了一些方法, ...
- go 学习 ---数据类型
25个关键字 程序声明:import, package 程序实体声明和定义:chan, const, func, interface, map, struct, type, var 程序流程控制:go ...
- /proc/meminfo分析(一)
本文主要分析/proc/meminfo文件的各种输出信息的具体含义. 一.MemTotal MemTotal对应当前系统中可以使用的物理内存. 这个域实际是对应内核中的totalram_pages这个 ...
- C#趣味程序---车牌号推断
甲说前两位同样,乙说后两位同样,丙说四位的车牌号刚好是一个数的平方.这个车牌号是多少? using System; namespace ConsoleApplication1 { class Prog ...
- iOS 关于 设计模式 与网友讨论实录
关于 设计模式 与网友讨论实录 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留 ...