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 [我希望大家在看完文章的时候,多做做练习,自己也可以想个场 ...
随机推荐
- exception Access restriction: The type 'BASE64Encoder' is not API
Created by Marydon on 1.情景展示 在eclipse中切换jdk版本后,报错信息为:exception Access restriction: The type 'BASE6 ...
- 基于CUDA的粒子系统的实现
基于CUDA的粒子系统的实现 用途: 这篇文章作为代码实现的先导手册,以全局的方式概览一下粒子系统的实现大纲. 科普: 对粒子进行模拟有两种基本方法: Eulerian(grid-based) met ...
- poi读取execl的日期
当execl中的列为日期格式时,后台读取到是一个数字,通过如下代码可以直接读取并转换到Date类型 HSSFDateUtil.getJavaDate(cell.getNumericCellValue( ...
- MySQL必知必会笔记(六)存储过程 游标 触发器
留印:http://blog.sina.com.cn/s/articlelist_1254871964_5_1.html 第二十三章 使用存储过程 MySQL5 中添加了存储过程的支持. ...
- Mint17 一些安装备忘
1,中文输入法: sudo apt-add-repository ppa:fcitx-team/dailybuild-fcitx-master sudo apt-get update sudo apt ...
- HDUOJ--4565 So Easy!
So Easy! Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Su ...
- 使用git 将自己的本地文件git到github上面的完整过程
1. 首先在github网站上新建一个仓库,复制仓库地址(HTTP形式或者SSH形式,后者利用SSH,在最后一步push 的时候可以不用输入用户名和密码). 2. 在本地某个你想要的(文件夹)目录 ...
- Linux GPIO子系统
一 概述 Linux内核中gpio是最简单,最常用的资源(和 interrupt ,dma,timer一样)驱动程序,应用程序都能够通过相应的接口使用gpio,gpio使用0-MAX_INT之间的整数 ...
- PMP考试终于结束了。。。
PMP考试昨天终于结束了,可以好好的先休息下了,先不管成绩了,通过这段时间的学习了解,发现PMP在实际工作中的运用 起的作用还很大,看样子以后要学习的东西还多着呢,先休息一周再说...
- linux文件系统管理的工作原理
一.系统在初始化时如何识别硬盘 1.系统初始时根据MBR的信息来识别硬盘,其中包括了一些执行文件就来载入系统,这些执行文件就是MBR里前面446bytes里的boot loader 程式,而后面的16 ...