■ Rule Allocate a class instance onto the managed heap using the new keyword and forget about it.
■ Rule If the managed heap does not have sufficient memory to allocate a requested object, a garbage collection will occur.
c2-=null;
! assigning a reference to null does not force the garbage collector
to remove the object from the heap.
A clean and compacted heap
■ Note Generations 0 and 1 are termed ephemeral generations.
it is not possible to directly call an object’s Finalize() method from a class instance .
the garbage collector will call an object’s Finalize() method before removing the object from memory.
// System.Object
public class Object
{
...
protected virtual void Finalize() {}
}
Building Finalizable Objects
Building Disposable Objects
Building Disposable Objects
Dispose pattern
public class DisposableResourceHolder : IDisposable
{
private SafeHandle resource; // handle to a resource
public DisposableResourceHolder()
{
this.resource = ... // allocates the resource
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing){
if (disposing){
if (resource!= null) resource.Dispose();
}
}
}
// bad design
public class DisposableResourceHolder : IDisposable
{
public virtual void Dispose(){ ... }
protected virtual void Dispose(bool disposing){ ... }
}
// good design
public class DisposableResourceHolder : Idisposable
{
public void Dispose(){ ... }
protected virtual void Dispose(bool disposing){ ... }
}
public class DisposableResourceHolder : IDisposable
{
bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if(disposed) return;
// cleanup
...
disposed = true;
}
}
public class DisposableResourceHolder : IDisposable
{
bool disposed = false;
SafeHandle resource; // handle to a resource
public void DoSomething()
{
if(disposed) throw new ObjectDisposedException(...);
// now call some native methods using the resource
...
}
protected virtual void Dispose(bool disposing)
{
if(disposed) return;
// cleanup
...
disposed = true;
}
}
public class Stream : IDisposable
{
IDisposable.Dispose(){
Close();
}
public void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
Если не удалось найти и скачать презентацию, Вы можете заказать его на нашем сайте. Мы постараемся найти нужный Вам материал и отправим по электронной почте. Не стесняйтесь обращаться к нам, если у вас возникли вопросы или пожелания:
Email: Нажмите что бы посмотреть