繁体   English   中英

dotMemory 和跟踪内存泄漏

[英]dotMemory and tracking memory leaks

我有我认为的基本 Web 应用程序 MVC,EF6。 用户有一个仪表板,其中显示了一个包含来自两个不同数据库系统的数据的表。 MSSQL 和 Informix(使用 IBM.Data.Informix)。

随着时间的推移,IIS 进程只会不断蚕食 ram。 我抓住了 dotMemory 来帮助我尝试定位它,但现在试图弄清楚如何读取这些数据。

我让网页保持打开状态,每 10 秒就有一个 Ajax 调用返回新数据。

第四张快照是在第三张快照几小时后拍摄的。 在此处输入图片说明

总数与下面的数字不匹配,但有些不应该是。

下面的图片似乎告诉我我的应用程序最多只使用 10mb。

在此处输入图片说明

我还在研究堆,但似乎这不是大块所在。

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

我仍在挖掘视频和指南以帮助我找出此问题的位置。 我使用了很多内置框架,我真的没有看到我使用的代码有问题,除非某处有错误或者我真的遗漏了我不应该在代码中做的事情。

数据库管理器

public class DatabaseManager : IDisposable
{
    private bool disposed = false;
    private SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);

    private PatientCheckinEntities db { get; set; }

    private IfxConnection conn { get; set; }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public DatabaseManager()
    {
        string ifxString = System.Configuration.ConfigurationManager.ConnectionStrings["ifx"].ConnectionString;
        conn = new IfxConnection(ifxString);
        db = new PatientCheckinEntities();
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            handle.Dispose();

            IfxClose();
            conn.Dispose();
            db.Dispose();
        }

        disposed = true;
    }

    private void IfxClose()
    {
        if (conn.State == System.Data.ConnectionState.Open)
        {
            conn.Close();
        }
    }

    private void IfxOpen()
    {
        if (conn.State == System.Data.ConnectionState.Closed)
        {
            conn.Open();
        }
    }

    public ProviderModel GetProviderByResourceID(string id)
    {
        ProviderModel provider = new ProviderModel();

        using (IfxDataAdapter ida = new IfxDataAdapter())
        {
            ida.SelectCommand = new IfxCommand("SELECT description FROM sch_resource WHERE resource_id = ? FOR READ ONLY", conn);
            IfxParameter ifp1 = new IfxParameter("resource_id", IfxType.Char, 4);
            ifp1.Value = id;
            ida.SelectCommand.Parameters.Add(ifp1);

            IfxOpen();
            object obj = ida.SelectCommand.ExecuteScalar();
            IfxClose();
            if (obj != null)
            {
                string name = obj.ToString();

                provider.ResourceID = id.ToString();
                string[] split = name.Split(',');

                if (split.Count() >= 2)
                {
                    provider.LastName = split[0].Trim();
                    provider.FirstName = split[1].Trim();
                }
                else
                {
                    provider.LastName = name.Trim();
                }

                ProviderPreference pp = db.ProviderPreferences.Where(x => x.ProviderID.Equals(id, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

                int globalWait = Convert.ToInt32(GetConfigurationValue(ConfigurationSetting.WaitThreshold));

                if (pp != null)
                {
                    provider.Preferences.DisplayName = pp.DisplayName;
                    provider.Preferences.WaitThreshold = pp.WaitThreshold.HasValue ? pp.WaitThreshold.Value : globalWait;
                }
                else
                {
                    provider.Preferences.WaitThreshold = globalWait;
                }
            }
        }

        return provider;
    }

    public List<PatientModel> GetCheckedInPatients(List<string> providers)
    {
        List<PatientModel> patients = new List<PatientModel>();

        foreach (string provider in providers)
        {
            List<PatientModel> pats = db.PatientAppointments
                        .Where(x => provider.Contains(x.ProviderResourceID)
                        && DbFunctions.TruncateTime(x.SelfCheckInDateTime) == DbFunctions.TruncateTime(DateTime.Now))
                            .Select(x => new PatientModel()
                            {
                                Appointment = new AppointmentModel()
                                {
                                    ID = x.AppointmentID,
                                    DateTime = x.AppointmentDateTime,
                                    ArrivalTime = x.ExternalArrivedDateTime
                                },
                                FirstName = x.FirstName,
                                LastName = x.LastName,
                                SelfCheckIn = x.SelfCheckInDateTime,
                                Provider = new ProviderModel()
                                {
                                    ResourceID = x.ProviderResourceID
                                }
                            }).ToList();

            patients.AddRange(pats.Select(x => { x.Provider = GetProviderByResourceID(x.Provider.ResourceID); return x; }));
        }

        using (IfxDataAdapter ida = new IfxDataAdapter())
        {
            ida.SelectCommand = new IfxCommand("SELECT arrival_time::char(5) as arrival_time FROM sch_app_slot WHERE appointment_key = ? FOR READ ONLY", conn);

            IfxOpen();
            foreach (PatientModel patient in patients)
            {
                ida.SelectCommand.Parameters.Clear();
                IfxParameter ifx1 = new IfxParameter("appointment_key", IfxType.Serial);
                ifx1.Value = patient.Appointment.ID;
                ida.SelectCommand.Parameters.Add(ifx1);

                using (IfxDataReader dr = ida.SelectCommand.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        if (dr.HasRows)
                        {
                            string arrival = dr["arrival_time"].ToString();

                            if (!string.IsNullOrWhiteSpace(arrival) && !patient.Appointment.ArrivalTime.HasValue)
                            {
                                PatientAppointment pa = new PatientAppointment();
                                pa.AppointmentID = patient.Appointment.ID;
                                pa.AppointmentDateTime = patient.Appointment.DateTime;
                                pa.FirstName = patient.FirstName;
                                pa.LastName = patient.LastName;

                                string dt = string.Format("{0} {1}", patient.Appointment.DateTime.ToString("yyyy-MM-dd"), arrival);
                                pa.ExternalArrivedDateTime = DateTime.ParseExact(dt, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
                                patient.Appointment.ArrivalTime = pa.ExternalArrivedDateTime;
                                pa.ProviderResourceID = patient.Provider.ResourceID;
                                pa.SelfCheckInDateTime = patient.SelfCheckIn;

                                db.PatientAppointments.Attach(pa);
                                db.Entry(pa).State = EntityState.Modified;
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
            IfxClose();
        }


        patients = patients.Select(x => { x.Appointment.WaitedMinutes = (int)Math.Round(((TimeSpan)x.Appointment.ArrivalTime.Value.Trim(TimeSpan.TicksPerMinute).Subtract(x.SelfCheckIn.Trim(TimeSpan.TicksPerMinute))).TotalMinutes); return x; }).ToList();

        List<PatientModel> sorted = patients.Where(x => !x.Appointment.ArrivalTime.HasValue).OrderBy(x => x.SelfCheckIn).ThenBy(x => x.Provider.ResourceID).ToList();
        sorted.AddRange(patients.Where(x => x.Appointment.ArrivalTime.HasValue).OrderBy(x => x.Appointment.DateTime).ThenBy(x => x.Provider.ResourceID));

        return sorted;
    }

    private string GetConfigurationValue(string id)
    {
        return db.Configurations.Where(x => x.ID.Equals(id)).Select(x => x.Value).FirstOrDefault();
    }
}

控制器

[HttpPost]
[Authorize]
public ActionResult GetCheckedIn(List<string> provider)
{
    DashboardViewModel vm = new DashboardViewModel();
    try
    {
        if (provider.Count > 0)
        {
            using (DatabaseManager db = new DatabaseManager())
            {
                vm.Patients = db.GetCheckedInPatients(provider);
            }
        }
    }
    catch (Exception ex)
    {
        //todo
    }
    return PartialView("~/Views/Dashboard/_InnerTable.cshtml", vm);
}

您的应用程序消耗大量本机内存,而不是 .NET 内存。 看看 .NET 内存消耗,它大约为 12Mb 并且不会密集增长。 似乎您没有在某些使用本机内存的对象上调用 Dispose 方法,例如数据库连接对象或类似的东西。 检查一些这样的对象,如果你不释放它们,数量会不断增加。

我看到您正在使用 System.xml.Schema .... 根据版本,将为每个大约 80K 的实例创建非托管内存泄漏。 因此,每使用 12 次,您就会在非托管内存中出现 1 兆的内存泄漏。 如果可能的话,不要每次都创建一个新的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM