今天重新学习了一下观察者模式,对我的思路产生了启发。进程监控程序之前写过几个,这回换一种思路,改用委托和事件来实现。我已经用序号将关键的几步标注,方便大家理顺思路。代码如下:

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#通过“委托和事件”的方式实现进程监控并与“普通方式”对比的更多相关文章

  1. C#窗体间常用的几种传值方式、以及委托与事件的详细介绍

    窗体间的传值,最好使用委托方式传值,开始之前,我们先来说一下委托与事件的关系. 委托:是一个类. 事件:是委托类型的一个特殊实例,只能在类的内部触发执行. 首先创建2个窗体,这里我们以form1为发送 ...

  2. .NET面试题系列[7] - 委托与事件

    委托和事件 委托在C#中具有无比重要的地位. C#中的委托可以说俯拾即是,从LINQ中的lambda表达式到(包括但不限于)winform,wpf中的各种事件都有着委托的身影.C#中如果没有了事件,那 ...

  3. .NET基础拾遗(4)委托、事件、反射与特性

    Index : (1)类型语法.内存管理和垃圾回收基础 (2)面向对象的实现和异常的处理基础 (3)字符串.集合与流 (4)委托.事件.反射与特性 (5)多线程开发基础 (6)ADO.NET与数据库开 ...

  4. [转载]C#深入分析委托与事件

    原文出处: 作者:风尘浪子 原文链接:http://www.cnblogs.com/leslies2/archive/2012/03/22/2389318.html 同类链接:http://www.c ...

  5. [转载]C#委托和事件(Delegate、Event、EventHandler、EventArgs)

    原文链接:http://blog.csdn.net/zwj7612356/article/details/8272520 14.1.委托 当要把方法作为实参传送给其他方法的形参时,形参需要使用委托.委 ...

  6. C#之委托与事件

    委托与事件 废话一堆:网上关于委托.事件的文章有很多,一千个哈姆雷特就有一千个莎士比亚,以下内容均是本人个人见解. 1. 委托 1.1 委托的使用 这一小章来学习一下怎么简单的使用委托,了解一些基本的 ...

  7. C# 关于委托和事件的妙文:通过一个例子详细介绍委托和事件的作用;Observer模式简介

    委托和事件在 .Net Framework中的应用非常广泛,然而,较好地理解委托和事件对很多接触C#时间不长的人来说并不容易.它们就像是一道槛儿,过了这个槛的人,觉得真是太容易了,而没有过去的人每次见 ...

  8. C#知识体系(二)用案例来理解委托与事件

    上一篇博客讲到了LinQ和lambda的常用方法 还有很多我们未知但c#设计团队已经为我们封装好的类和方法.随着我们不断的熟悉C#语言,渐渐的就会接触到其他的知识点,委托.事件.反射.线程.同步,异步 ...

  9. [转]大白话系列之C#委托与事件讲解(三)

    本文转自:http://www.cnblogs.com/wudiwushen/archive/2010/04/21/1717378.html [我希望大家在看完文章的时候,多做做练习,自己也可以想个场 ...

随机推荐

  1. exception ORA-00923: FROM keyword not found where expected

      exception ORA-00923: FROM keyword not found where expected CreationTime--2018年8月16日10点41分 Author:M ...

  2. 【Linux】gvim封装至gvi命令

    方法1:使用脚本 #!/bin/bash - #============================================================================ ...

  3. HDUOJ----4006The kth great number(最小堆...)

    The kth great number Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65768/65768 K (Java/Oth ...

  4. HDUOJ----最少拦截系统

    最少拦截系统 Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other) Total Submis ...

  5. js中的let和var

    在ES6中,应该尽量使用const和let来声明变量,而尽量避免使用var. var的缺点是它的作用域比较混乱,使用let能够保证清晰的作用域. 下面看一个小例子. var x = 3; if(x== ...

  6. Selenium-Grid工作原理

    selenium-grid是由一个hub节点和若干个代理节点组成.hub用来管理各个代理节点的注册和状态信息,并且接受远程客户端代码的请求调用,然后把请求的命令再转发给代理节点来执行.使用seleni ...

  7. Form_Form Builder的常用方法(概念)

    2014-07-07 Created By BaoXinjian

  8. Factory - 工厂模式

    在面向对象编程中, 最通常的方法是一个new操作符产生一个对象实例,new操作符就是用来构造对象实例的.但是在一些情况下, new操作符直接生成对象会带来一些问题.举例来说, 许多类型对象的创造需要一 ...

  9. Trie树 - 字典树

    1.1.什么是Trie树 Trie树,即字典树,又称单词查找树或键树,是一种树形结构.典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计.它的优点是最大限 ...

  10. Android仿联系人列表分组悬浮列表实现,自己定义PinnedHeaderListView实现

    效果 (关于gif怎么生成的.我先录手机的屏幕得到mp4文件.然后用这个网址:https://cloudconvert.com/mp4-to-gif 进行的mp4转换gif,使用的时候须要又一次选择g ...