C#通过“委托和事件”的方式实现进程监控并与“普通方式”对比

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

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

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 = 0;
                foreach (var process in processes)
                {
                    if (string.Compare(process.ProcessName, processComboBox.Text, true) == 0)
                    {
                        count++;
                    }
                }
                if (count == 0)
                {
                    //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 = 0;
                foreach (var process in processes)
                {
                    if (string.Compare(process.ProcessName, processComboBox.Text, true) == 0)
                    {
                        count++;
                    }
                }
                if (count == 0)
                {
                    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 = 0;
                foreach (var process in processes)
                {
                    if (string.Compare(process.ProcessName, processComboBox.Text, true) == 0)
                    {
                        count++;
                    }
                }
                if (count == 0)
                {
                    //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() == 0)
                {
                    //2.Active the action.
                    processExit("The target process has been dispeared.");
                    flag = false;
                }
            } while (flag);
        }
    }
}

 

相关文章
|
5月前
|
存储 监控 算法
电脑监控管理中的 C# 哈希表进程资源索引算法
哈希表凭借O(1)查询效率、动态增删性能及低内存开销,适配电脑监控系统对进程资源数据的实时索引需求。通过定制哈希函数与链地址法冲突解决,实现高效进程状态追踪与异常预警。
261 10
|
5月前
|
存储 机器学习/深度学习 监控
网络管理监控软件的 C# 区间树性能阈值查询算法
针对网络管理监控软件的高效区间查询需求,本文提出基于区间树的优化方案。传统线性遍历效率低,10万条数据查询超800ms,难以满足实时性要求。区间树以平衡二叉搜索树结构,结合节点最大值剪枝策略,将查询复杂度从O(N)降至O(logN+K),显著提升性能。通过C#实现,支持按指标类型分组建树、增量插入与多维度联合查询,在10万记录下查询耗时仅约2.8ms,内存占用降低35%。测试表明,该方案有效解决高负载场景下的响应延迟问题,助力管理员快速定位异常设备,提升运维效率与系统稳定性。
281 4
|
7月前
|
存储 机器学习/深度学习 监控
公司监控软件有哪些?监测方案:基于布隆过滤器的 C# 异常行为检测实践探索
本文探讨了布隆过滤器在公司监控软件中的技术应用,介绍其原理、优势及C#实现代码,助力企业高效构建数据安全防护体系。
192 0
|
9月前
|
监控 算法 安全
公司电脑监控软件关键技术探析:C# 环形缓冲区算法的理论与实践
环形缓冲区(Ring Buffer)是企业信息安全管理中电脑监控系统设计的核心数据结构,适用于高并发、高速率与短时有效的多源异构数据处理场景。其通过固定大小的连续内存空间实现闭环存储,具备内存优化、操作高效、数据时效管理和并发支持等优势。文章以C#语言为例,展示了线程安全的环形缓冲区实现,并结合URL访问记录监控应用场景,分析了其在流量削峰、关键数据保护和高性能处理中的适配性。该结构在日志捕获和事件缓冲中表现出色,对提升监控系统效能具有重要价值。
245 1
|
10月前
|
存储 监控 算法
局域网上网记录监控的 C# 基数树算法高效检索方案研究
在企业网络管理与信息安全领域,局域网上网记录监控是维护网络安全、规范网络行为的关键举措。随着企业网络数据量呈指数级增长,如何高效存储和检索上网记录数据成为亟待解决的核心问题。基数树(Trie 树)作为一种独特的数据结构,凭借其在字符串处理方面的卓越性能,为局域网上网记录监控提供了创新的解决方案。本文将深入剖析基数树算法的原理,并通过 C# 语言实现的代码示例,阐述其在局域网上网记录监控场景中的具体应用。
213 7
|
12月前
|
存储 监控 算法
员工电脑监控系统中的 C# 链表算法剖析-如何监控员工的电脑
当代企业管理体系中,员工电脑监控已成为一个具有重要研究价值与实践意义的关键议题。随着数字化办公模式的广泛普及,企业亟需确保员工对公司资源的合理利用,维护网络安全环境,并提升整体工作效率。有效的电脑监控手段对于企业实现这些目标具有不可忽视的作用,而这一过程离不开精妙的数据结构与算法作为技术支撑。本文旨在深入探究链表(Linked List)这一经典数据结构在员工电脑监控场景中的具体应用,并通过 C# 编程语言给出详尽的代码实现与解析。
223 5
|
存储 监控 算法
企业内网监控系统中基于哈希表的 C# 算法解析
在企业内网监控系统中,哈希表作为一种高效的数据结构,能够快速处理大量网络连接和用户操作记录,确保网络安全与效率。通过C#代码示例展示了如何使用哈希表存储和管理用户的登录时间、访问IP及操作行为等信息,实现快速的查找、插入和删除操作。哈希表的应用显著提升了系统的实时性和准确性,尽管存在哈希冲突等问题,但通过合理设计哈希函数和冲突解决策略,可以确保系统稳定运行,为企业提供有力的安全保障。
|
C#
C#一分钟浅谈:委托与事件的实现方式
本文详细介绍了C#编程中委托与事件的基础知识及应用场景。首先解释了委托的概念,包括定义与使用方法;接着介绍了事件这一基于委托的特殊类型,展示了如何在类中定义事件及跨类订阅与处理事件;最后讨论了常见问题如事件未处理异常、重复订阅及内存泄漏等,并提出了相应的解决方案。通过本文,读者将全面掌握委托与事件的使用技巧,提升应用程序的设计与开发水平。
417 7
由浅入深理解C#中的事件
由浅入深理解C#中的事件
301 19
|
监控 安全 C#
使用C#如何监控选定文件夹中文件的变动情况?
使用C#如何监控选定文件夹中文件的变动情况?
400 19