现在的位置: 首页 > 综合 > 正文

C#监控内存开销,调用外部命令

2017年10月21日 ⁄ 综合 ⁄ 共 3625字 ⁄ 字号 评论关闭

                        Process[] processes = Process.GetProcessesByName(strProcessName);
                        long memoryUsed = processes[0].PrivateMemorySize64;
                        LogHelper.log("当前开销 " +memoryUsed+" Bytes");
                        
                        if(memoryThreshold*1024*1024<memoryUsed)
                        {
                            killProcess(strProcessName);
                            //重启
                            //String strCommand="C:\\Windows\\System32\\cmd.exe";
                            String strCommand = textBoxCommand.Text.Trim();
                            ShellExecute(IntPtr.Zero, null, strCommand, null, null, 5);//#define SW_SHOW 5
                            break;
                        }

以上是检查内存开销,关闭进程,调用外部命令的C#代码。

其中,ShellExecute的定义如下:

        [DllImport("shell32.dll ")]
        public static extern int ShellExecute(IntPtr hwnd, 
            String lpszOp,
            String lpszFile,
            String lpszParams,
            String lpszDir, 
            int FsShowCmd);

整个的源代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

using System.IO;

using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

namespace Reseter
{
    public partial class FormReset : Form
    {

        [DllImport("Kernel32.dll")]
        private static extern bool AllocConsole();

        [DllImport("shell32.dll ")]
        public static extern int ShellExecute(IntPtr hwnd, 
            String lpszOp,
            String lpszFile,
            String lpszParams,
            String lpszDir, 
            int FsShowCmd);


        [DllImport("kernel32.dll",
            EntryPoint = "GetStdHandle",
            SetLastError = true,
            CharSet = CharSet.Auto,
            CallingConvention = CallingConvention.StdCall)]
        private static extern IntPtr GetStdHandle(int nStdHandle);

        private const int STD_OUTPUT_HANDLE = -11;
        //private const int MY_CODE_PAGE = 936;  设置汉字编码


        public FormReset()
        {
            InitializeComponent();
        }

        private void FormReset_Load(object sender, EventArgs e)
        {
            setOutput();
            button1.Hide();
        }

        private void buttonMonitor_Click(object sender, EventArgs e)
        {
            String strProcessName=textBoxProcessName.Text.Trim();
            try
            {
                double memoryThreshold = Convert.ToDouble(textBoxMemorySize.Text.Trim());
                LogHelper.log("开始监控进程"+strProcessName+",当内存开销大于"+"M时,会关闭进程,并运行重启命令");
                while (true)
                {
                    if (isProcessRunning(strProcessName) == false)
                    {
                        LogHelper.log( "当前系统中没有运行" + strProcessName);
                        break;
                    }
                    else
                    {
                        Process[] processes = Process.GetProcessesByName(strProcessName);
                        long memoryUsed = processes[0].PrivateMemorySize64;
                        LogHelper.log("当前开销 " +memoryUsed+" Bytes");
                        
                        if(memoryThreshold*1024*1024<memoryUsed)
                        {
                            killProcess(strProcessName);
                            //重启
                            //String strCommand="C:\\Windows\\System32\\cmd.exe";
                            String strCommand = textBoxCommand.Text.Trim();
                            ShellExecute(IntPtr.Zero, null, strCommand, null, null, 5);//#define SW_SHOW 5
                            break;
                        }
                    }
                    LogHelper.log("2分钟监控一次");
                    System.Threading.Thread.Sleep(60 * 1000);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("请输入一个合法的整数");
                textBoxMemorySize.Text = "";
                textBoxMemorySize.Focus();
            }
            
        }

        //关闭进程
        public void killProcess(String strName)
        {
            Process[] processList = System.Diagnostics.Process.GetProcessesByName(strName);
            if (processList.Length > 0)
            {
                for (int i = 0; i < processList.Length; i++)
                {
                    LogHelper.log("关闭" + strName + "进程");
                    processList[i].Kill();
                }
            }
        }

         /**
         * 判断一个进程是否存在,去掉后缀名,例如检查excel
         * */
        private bool isProcessRunning(String strName)
        {
            Process[] iFindProcess = System.Diagnostics.Process.GetProcessesByName(strName);
            if (iFindProcess.Length > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        private void setOutput()
        {
            AllocConsole();
            IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
            SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);
            FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
            Encoding encoding = System.Text.Encoding.GetEncoding(Console.OutputEncoding.CodePage);
            StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
            standardOutput.AutoFlush = true;
            Console.SetOut(standardOutput);

        }

        private void textBoxCommand_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //String strCommand = "C:\\Windows\\System32\\cmd.exe";
            String strCommand = "C:\\hello.bat";
            //String strCommand = textBoxCommand.Text.Trim();
            ShellExecute(IntPtr.Zero, null, strCommand, null, null, 5);//#define SW_SHOW 5
        }
    }
}

抱歉!评论已关闭.