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 [我希望大家在看完文章的时候,多做做练习,自己也可以想个场 ... 
随机推荐
- x-code的使用技巧心得
			xcode是苹果开发的一款图形化,而且用户交互很好的开发软件开发工具. 它支持 C语言 o-bjiect语言 c++ 等多种语言的开发.功能强大,俗话说的好,工欲善其事,必先利其器,以下将描写叙述一下 ... 
- python之函数用法bin()
			# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法bin() #bin() #说明:一个整数转换为一个二进制字符串 ''' bin(.. ... 
- urlretrieve 如何给文件下载设置下载进度?
			#python #xiaodeng #如何给文件下载设置下载进度? import urllib def callbackinfo(down,block,size): ''' 回调函数: down:已经 ... 
- css3中-moz、-ms、-webkit 是什么意思
			-moz代表firefox浏览器私有属性-ms代表IE浏览器私有属性-webkit代表chrome.safari私有属性 私有属性例如:设置div圆角的大小 -webkit-border-radius ... 
- 如何架设部署V2EX社区/论坛(Google App Engine版)
			1.What's V2EX? 关于这个问题,我们可以看看其作者Livid早期自己的V2EX社区的介绍: What's V2EX? 这是很多人都问过的问题,而我一直都没有做出一个明确的解答.因为我实在觉 ... 
- ListView中Button事件
			为了解决ListView中Item里的Button独立事件响应,能够採用下面方法: 在BaseAdapter的getview里加入加粗代码: <span style="font-siz ... 
- HDUOJ----2489 Minimal Ratio Tree
			Minimal Ratio Tree Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Other ... 
- 【LeetCode】144. Binary Tree Preorder Traversal (3 solutions)
			Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' valu ... 
- 利用腾讯云免费证书打造全https站
			什么是https? 超文本传输安全协议(Hypertext Transfer Protocol Secure,缩写为HTTPS)是一种网络安全传输协议http是HTTP协议运行在TCP之上,所有传输的 ... 
- C# 自定义文件格式并即时刷新注册表 非关闭explorer
			转自:http://blog.csdn.net/zhangtirui/article/details/4309492 最近公司在做一个项目 用到关于自定义格式的文件,但在注册表图标更改后 文件图标 ... 
