Advanced Search
dispose()
method called automatically from stateful if not defined.
In some cases dispose is required for example in CameraPreview
, Timer
etc.. you have to close the stream.
When closing the stream is required you have to use it in dispose method.
dispose()
is used to execute code when the screen is disposed. Equal to onDestroy()
of Android.
Example:
@override
void dispose() {
cameraController?.dispose();
timer.cancel();
super.dispose();
}
If a class implements IDisposable, you really should dispose of it correctly. It is not just about relying on the garbage collector, the disposable class could have open handles / COM objects that need to be correctly cleaned up that you cannot guarantee that the GC will handle.
Ideally you should make myclass
implement IDisposable and clean up your disposable objects in the dispose method. If you truly cannot determine when to dispose your instance of myclass
then you can implement logic in the destructor method for myclass
to call the dispose method.
public class myclass : IDisposable
{
private Semaphore _sync;
myclass ()
{
_sync = new Semaphore(1,1);
}
doasync()
{
_sync.WaitOne();
//do some stuff
_sync.Release();
}
public void Dispose()
Dispose(true);
GC.SuppressFinalize(this);
{
protected void Dispose(bool isDisposing)
{
var sync=Interlocked.Exchange(ref _sync,null);
if (sync !=null) sync.Dispose();
}
// This is for when you cannot determine when to dispose of your object
void ~myclass() {
Dispose(false);
}
}
using
is used for local variables in a function to implicitly dispose the object, but when it is a member of a class you should dispose it when the class is disposed.
class YourClass : IDisposable
{
....
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_stream.Dispose();
}
}
}
In the must used IDisposable
implementation, you create a protected Dispose(bool managed)
method which always disposes the unmanaged resources you use. By calling your protected Dispose(false)
method from your finalizer, you'll dispose the lock as required. The lock is managed, do you'll only dispose it when Dispose(true)
is called, where true
means that managed objects need to be disposed. Otherwise, when the public Dispose()
is called explicitly, it calls the protected Dispose(true)
and also GC.SuppressFinalize(this)
to prevent the finalizer from running (because there is nothing to dispose of anymore).
Because you never know when the user is done with the enumerator, you have no other option than documenting that the user has to dispose the object. You might want to propose that the user uses a using(){ ... }
construction, which automatically disposes the object when done.