What happens to a thread if it is running a method in an object that was freed by exiting a using block?
Example:
using (SomeObject obj = new SomeObject ()) { obj.param = 10 ; Thread newThread = new Thread(() => { obj.Work(); }); newThread.Start(); } ...
obj.Work() is running on a new thread but obj is an IDisposable object that would normally get released when the using block exits. What happens if the thread continues running after the using block ends? Will the object get disposed only after the thread completes? Or will the thread break?
Thanks.
Interesting things will happen.
Specifically, the dispose method on SomeObject will be called, either before or after Work has been called as it may or may not have been scheduled to run by that point.
After that, it depends on what the dispose method of SomeObject does; if it, say, releases a SqlConnection that isn't used in 'Work', then there shouldn't be an issue; if however SomeObject expects that it hasn't been disposed, you'll probably have an exception thrown in that thread.
Remember that IDisposable
is just a pattern and doesn't free the memory associated with the object. This being the case the close of the using
block will call obj.Dispose
and the other thread that is using obj
will continue to run.
This will create strange issues for you since obj's
state may be changed while the other thread is using it (it all depends on how the Dispose
method is implemented). Needless to say this application of IDisposable
, threading, and the using
statement will be problematic at best.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With