c# - Destructor never gets called -
this question has answer here:
- why destructor never run? 6 answers
i have class class
creates thread
in it's constructor. thread runs while(true)
loop reading non-critical data netstream
. thread aborted destructor:
~class() { _thread.abort(); _thread = null; }
when program wants end use of class
's instance - classinstance
, calls:
classinstance = null; gc.collect;
i thought means ~class()
caller automatically @ point - it's not.
this thread keeps running after application.exit()
, returning main()
.
the crucial bit of code not included; how thread started , method running. if had make guess started thread passing instance method of class
. class instance still rooted running of thread. attempt stop thread in finalizer, finalizer never run because instance still rooted leading catch-22 situation.
also, mentioned thread running non-critical code , justification using thread.abort
. not enough reason. hard control threadabortexception
injected thread , result may corrupt critical program data structures did not anticipate.
use new cooperative cancellation mechanisms included tpl. change while (true)
loop poll cancellationtoken instead. signal cancellation in dispose
method when implement idisposable
. not include finalizer (destructor in c# terminology). finalizers intended used clean unmanaged resources. since have not indicated unmanaged resources in play pointless have finalizer. not have include finalizer when implementing idisposable
. in fact, considered bad practice have 1 when not needed.
public class class : idisposable { private task task; private cancellationtokensource cts = new cancellationtokensource(); class() { task = new task(run, cts.token, taskcreationoptions.longrunning); task.start(); } public void dispose() { cts.cancel(); } private void run() { while (!cts.token.iscancellationrequested) { // stuff goes here. } } }
Comments
Post a Comment