Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDisposable, ObjectDisposedException, and threadsafe types

Is there any point in keeping track of the classic bool disposed field on an otherwise threadsafe type for the purposes of conditionally throwing an ObjectDisposedException at the beginning of all primary exposed methods?

I've seen this pattern recommended in a few places online but I'm not sure if the authors are using it correctly, so this question assumes that they are.

In such a scenario, it seems that the only way to ensure that the disposed condition is true beyond the condition's evaluation is to use a synchronization mechanism such as lock() over the entire body of each exposed member including the Dispose(bool) method. Wouldn't this make the type effectively single-threaded again?

And if this is true, then there'd be no point in using it, and therefore you can't rely on the ObjectDisposedException mechanism in some IDisposable implementations - so then why would we EVER employ this mechanism if it isn't necessary?

====

I guess IDisposable and ObjectDisposedException just don't go together for thread-safe types.

like image 658
Jason Kleban Avatar asked Feb 11 '10 18:02

Jason Kleban


2 Answers

Perhaps a more efficient way of making a threadsafe object not become disposed while a method is running is to use a ReaderWriterLockSlim. Have all the public methods obtain a read lock while executing and release it when they're done. Have Dispose obtain a writer lock. It will wait till all the other methods are done before it obtains it's write lock. It then sets isDisposed inside the write lock which it exclusively holds. Any calls to public methods after Dispose is done can see isDisposed and throw the ObjectDisposedException.

ReaderWriterLockSlim

http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx

like image 50
Samuel Neff Avatar answered Nov 12 '22 03:11

Samuel Neff


If the behavior of your object will be different if it is already disposed, and if it's likely that it will be used after it's been disposed, then you need to keep track of this. It's better to throw ObjectDisposedException than to throw whatever random exception that will occur if the object is already disposed and you don't check first.

like image 23
John Saunders Avatar answered Nov 12 '22 04:11

John Saunders