c# - Logic to ensure a method is only called once -


i'm writing idisposable class, intended used in multi-threaded environment. want make sure dispose() called once. far came with:

int _isdisposingasint = 0; public void dispose() {     if (interlocked.exchange(ref _isdisposingasint , 1) == 0)         return;              // dispose code     .... } 

is there more elegant way of achieving this?

edit
important addition - not intend call dispose() multiple threads. intend use _isdisposingasint signal background thread, listens serial port, , may terminate ungracefully, should not re-throw exception.

firstly, declare _isdisposingasint volatile because want updated in threads.

secondly, need declare object , lock it/exchange it's value in order know have been @ dispose. did in 1 line, there no shorter that. can in efficient way:

if(interlocked.compareexchange(ref _isdisposingasint , 1 , 0) == 0) 

this way check before exchange if value 0, , u save bus , blocking threads.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -