Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# exiting a using() block with a thread still running onthe scoped object

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.

like image 912
yitz Avatar asked Jun 23 '09 14:06

yitz


2 Answers

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.

like image 144
CoderTao Avatar answered Oct 13 '22 19:10

CoderTao


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.

like image 43
Andrew Hare Avatar answered Oct 13 '22 20:10

Andrew Hare