Given the semantics of IDisposable, what should Dispose do besides clearing resources, of course?
I have seen that many classes use the Dispose method to initiate shutdown processes and some other things, and not just to "clean up resources". For example, if you have a thread inside a class that needs to be disconnected, do you expect the Dispose call to elegantly disconnect that thread ?
IMHO I would apply the Stop / Shutdown method to this object and gracefully disable the thread there, while in Dispose I would check when the thread is still alive, just to call Abort on it (kill style :)).
The same example can be with timers and all other resources that may have some kind of completion process before completing work with this object.
Two examples of conflicting constructs in .NET:
, IDisposable, IDisposable Object, , , IDisposable.Dispose , (, IDisposable, - ). Dispose , , .
IDisposable
Object
IDisposable.Dispose
Dispose
, , , , Dispose , . Dispose ( ) , , . , , , , ( , , ). , , Dispose , , , , .
, dispose -. :
public class UsingBase : IDisposable { protected Action end; public UsingBase(Action start, Action end) { this.end = end; if (start != null) start(); } public void Dispose() { if (end != null) end(); } public void Cancel() { end = null; } } class HideCursor : UsingBase { public HideCursor() : base(() => Console.CursorVisible = false, () => Console.CursorVisible = true) { } } public static void DisplayTitle(...) { ... using (new HideCursor()) { //Display the title } ... }
, API ASP.net.
@using (Html.BeginForm()) { ... }
, , , Dispose ?
, , , . , , " " "", .
, , :
using (var blah = new Blah()) { ... ... ... Blah.SpecialDispose(); }//Blah.Dispose();
, - (, ).
Edit:
. , - Dispose. , Dispose "". , . , , Dispose " " . , , . , , .