1

不确定如何处理此类,因为由于应用程序中的内存泄漏导致它变慢,我需要释放资源。我不确定如何处理下面的类,因为某些属性没有实现 IDisposable。我对 c# 相当陌生,所以尽量不要使响应过于复杂。

public class CellItem: IDisposable
    {
        private Timer foo = new Timer();

        public int MedicationDispenseId { get; set; }
        public Enumerations.Timeslot Timeslot { get; set; }
        public DateTime DateAdministered { get; set; }

        protected override void Dispose(bool disposing)
        {
            disposing = true;
            Dispose(disposing);
        }

    }
4

4 回答 4

7

代码中有一个错误:

protected override void Dispose(bool disposing)
{
            disposing = true;
            Dispose(disposing);
}

是递归的,如果只是在堆栈空间用完之前坐在那里一会儿。

要回答您的问题:如果是您的代码,那么只需更改Dispose方法以释放适当的资源。如果不是,那么您将不得不询问编写它的人来修复它,或者考虑编写您自己的(无错误)版本。

于 2013-08-23T13:05:45.263 回答
3
    protected override void Dispose(bool disposing)

您没有实现 IDisposable.Dispose() 方法,因此此代码无法编译。受保护的 Dispose(bool) 方法是一次性模式的产物。它仅在您的类具有终结器或您的类派生自实现一次性模式的基类时使用。也不是这样。

所以保持简单,只需实现 Dispose():

    public void Dispose()
    {
        foo.Dispose();
    }
于 2013-08-23T13:10:41.973 回答
0

The Disposing flag is not a field which says whether the disposal has started for the class, but should instead be regarded as a dummy parameter to which the value true should be passed when the protected virtual method is called from the parameterless Dispose method which implements the interface. The parameter was originally designed so as to allow a common "patch point" for derived classes which want to add functionality to both Dispose and Finalize (destructor) methods, but in practice it's almost never appropriate for a derived or unsealed class to implement Finalize code unless the class is derived directly from Object or from a class whose whole purpose centers around such cleanup.

Note that unlike most interfaces, the IDisposable "contract" doesn't impose any obligations on the class which implements it, but instead exists as a standard means via which many types of classes can impose certain transferable contractual obligations on code which requests their construction. A typical IDisposable object will ask some other entity to do something on its behalf until further notice, will promise that other entity that it will be informed when its services are no longer required, and will use its Dispose method for the purpose of giving such notice. The constructor contract for many classes which implement IDisposable will require that the caller either ensure that before it abandons the object it will either Dispose it or give it to some other entity that promises to do so.

于 2013-08-27T21:54:39.507 回答
0

尝试阅读这些资源以帮助您入门:

一次性

http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

使用关键字

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

于 2013-08-23T13:05:39.577 回答