C# exiting a using() block with a thread still running onthe scoped object
c#, multithreading, using-statement
Solution
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.
Problem
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.