The proper course of action would be for the creators of some Disposable objects to go slightly against Microsoft's "rule" that performing any action on a disposed object should throw an exception, and instead follow the more general rule that an exception should be thrown any time a method's post-conditions can't be met. If the purpose of a Cancel method is to ensure that nobody will continue to regard a job as being live, and even before the Cancel method is called everyone regards the job as being dead, then the post-condition for the method is satisfied regardless of whether the object is disposed.
Generally, code outside a well-designed object shouldn't need to query whether it's been disposed, except possibly to assert that it has been. Instead, the object itself should provide methods whose meaning on a disposed object would be clear and unambiguous. Those methods might internally use an IsDisposed flag, but would have to use whatever locking was necessary to prevent race conditions. In general, the pattern
if (!myThing.isDisposed)
myThing.DoSomething();
is an indication that myThing should really support a DoSomethingIfNotDisposed method (possibly called TryDoSomething). If you can't do that, my inclination might be to write your own DoSomethingIfNotDisposed extension method and use a Try/Catch to stifle an ObjectDisposedException (or whatever particular exception the object would throw).
CancellationToken
is used for synchronization. It happens whe two threads try to cancel the job at the same time. Maybe a lock over it helps? – LillisCancellationToken
, that can't be done. You're diposing of theCancellationTokenSource
. – PavidManualResetEvent
? (Though I'm agreeing with @lassee, seems the implementation is wrong. – Nanice