c# 4.0 - Is it safe to call Dispose on an instance from event handler? -


public class mytask : idisposable { ... }  mytask task = new mytask(() => sometask);  task.completed += (s, e) => {     // result     ...     // dispose of instance     ((mytask)s).dispose(); };  // execute task task.execute(); 

clearly cannot tell when task completed, actual place, see it, can dispose of instance in completed event.

is safe do?

there is, alas, no general rule when safe call dispose. if microsoft had specified dispose must safe call @ time when object isn't in use, complying such rule seldom have been difficult; in cases class might not able perform necessary cleanup immediately(*), possible set flag and/or otherwise arrange have necessary cleanup performed @ next opportunity. unfortunately, microsoft not specify dispose implementations have handle asynchronous dispose requests, nor there general way object holds last useful reference idisposable instance ask notification when safe dispose.

despite general lack of assurance when safe call dispose, many particular classes implement dispose offer guarantees when may safely called. if 1 knows particular object of type can safely disposed in particular context, 1 may dispose then. in cases event object may opportunity dispose in threading context know about, , disposing object within event handler make sense, should safe dispose of object. properly-written event handlers should prepared possibility object sending event may disposed between time system decides should run, , time runs them.

(*) essential purpose of idisposable allow object notify entities outside acting on behalf detriment of other entities, should no longer [e.g. tell file system should no longer grant object exclusive access file]. such action referred "releasing resources". fact holds last surviving reference object may imply no other thread can using object, not imply no other thread using non-thread-safe entities resources need released.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -