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

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. JS禁止后退键(backspace)使浏览器后退

    背景说明: 今天项目测试中,同事发现一个Bug,当键盘敲下后退键(Backspace)后,浏览器自动后退,不符合需求,故建议禁止浏览器后退键. 提出需求: 当键盘敲下后退键(Backspace)后 1 ...

  2. 微信小程序条码、二维码生成模块

    代码地址如下:http://www.demodashi.com/demo/13994.html 一.前期准备工作 软件环境:微信开发者工具 官方下载地址:https://mp.weixin.qq.co ...

  3. HDUOJ---1867 A + B for you again

    A + B for you again Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Othe ...

  4. WCF与WPF

    1. WCF(Windows Communication Foundation )是一个统一的,可用于建立安全,可靠的面向服务的应用高效的开发平台.WCF是构建安全可靠的事务性服务的统一框架.它是一种 ...

  5. Ubuntu 10.04 安装流程

    ubuntu 10.04 安装流程   需安装libxrender-dev才能跑html5           来自为知笔记(Wiz)

  6. 如何不让DataGridView自动生成列

    如果不想让DataGridView自动生成与数据源对应的列, 只需要把属性AutoGenerateColumns设为false即可. 需要注意: 在界面设计的属性窗口中是看不到AutoGenerate ...

  7. redhat 6.4 安装VirtualBox自动增强功能功:unable to find the sources of your current Linux kernel

    redhat 6.4 安装VirtualBox自动增强功能功能的时候提示: building the main Guest Additions module FAILED unable to find ...

  8. asp.net 在线解压缩文件类

    using System; using System.Collections.Generic; using System.Text; using System.IO; using Microsoft. ...

  9. SICP 习题 (2.8) 解题总结:区间的减法

    SICP 习题 2.8 须要我们完毕区间运算的减法.区间运算的加法书中已经有了,代码例如以下: (define (add-interval x y) (make-interval (+ (lower- ...

  10. python 中hive 取日期时间的方法

    #!/usr/bin/env python3 import sys import os import time, datetime sys.path.append(os.getenv('HIVE_TA ...