views:

521

answers:

4

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.

+4  A: 

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.

Andrew Hare
+1  A: 

When the using block is exited on the main thread, it will .Dispose() the object, which could cause all sorts of fun concurrency problems. However, the object won't be garbage collected--it will remain, but in an invalid state, depending on your implementation of .Dispose().

Matt
+9  A: 

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.

CoderTao
Interesting things, good one.
Groo
For some reason, it makes me think of Mos Def in The Italian Job: "I had a bad experience."
Robert Rossney
+1  A: 

The object will call Dispose at the end of the block. It will continue to run, but obj will become unstable as Dispose is suppose to close connections etc. Now it is possible that obj would be setup to check if something is in use and close it afterwards, but I wouldn't count on this unless you've written the object to handle this.

Kevin