How to find out an object has disposed?

Xaqron picture Xaqron · Apr 13, 2011 · Viewed 24.8k times · Source

I have a multi-threaded application and a CancellationToken is used as a shared object. Every thread can trigger it to tell the other threads the job is cancelled. Then one thread does the clean-up and disposes every object like this CancellationToken. Then if a thread tries to use it, an exception is raised:

The CancellationTokenSource has been disposed.

How can I find out an object is disposed before using it?

Answer

Lasse V. Karlsen picture Lasse V. Karlsen · Apr 13, 2011

Well, according to Reflector, CancellationTokenSource has an internal IsDisposed method that could've told you, but since it's internal, you're not supposed to call it.

In any case, if one thread yanks out data structures and objects other threads depend on, then don't do that. Fix your code and leave those objects live for the duration of their need.

In other words, wait for those other threads to finish needing the CancellationTokenSource before you dispose of it.