欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

c#程序定期把内存信息记录到log日志示例

时间:2021-03-29 09:40:58|栏目:.NET代码|点击:

设立一个定时器tmrMonitor,该定时器会在程序运行时不断把程序的占用内存和占用线程数写到LOG\MEM目录下。
我设置的定时器间隔是3000毫秒,记录后的信息可以用来分析一段时间内程序的运行状况,比如内存泄漏问题。

复制代码 代码如下:

/// <summary>
/// Timer组件tmrMonitor的Tick事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tmrMonitor_Tick(object sender, EventArgs e)
{
    string LogAddress = Environment.CurrentDirectory + "\\Log";
    if (!Directory.Exists(LogAddress + "\\MEM")) //需要System.IO
    {
        Directory.CreateDirectory(LogAddress + "\\MEM");
    }

    LogAddress = String.Concat(LogAddress, "\\MEM\\",
        DateTime.Now.Year, '-', DateTime.Now.Month, '-',
        DateTime.Now.Day, "_mem.log");

    //需要 System.Diagnostics;
    Process currentProcess = Process.GetCurrentProcess();

    StreamWriter sw = new StreamWriter(LogAddress, true);
    sw.WriteLine('[' + DateTime.Now.ToString() + ']');
    sw.WriteLine("进程标识: " + currentProcess.Id.ToString());
    sw.WriteLine("进程名称: " + currentProcess.ProcessName.ToString());
    sw.WriteLine("占用内存: " +
        (currentProcess.WorkingSet64 / 1024).ToString() + "KB");
    sw.WriteLine("线程数量: " + currentProcess.Threads.Count.ToString());
    sw.WriteLine();
    sw.Close();
}

上一篇:Asp.net静态方法之Grid转DataTable方法实现步骤

栏    目:.NET代码

下一篇:C#编写的艺术字类实例代码

本文标题:c#程序定期把内存信息记录到log日志示例

本文地址:http://www.codeinn.net/misctech/90111.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有