Note that there are some explanatory texts on larger screens.

plurals
  1. POIs C#'s using statement abort-safe?
    text
    copied!<p>I've just finished reading "C# 4.0 in a Nutshell" (O'Reilly) and I think it's a great book for a programmer willing to switch to C#, but it left me wondering. My problem is the definition of <code>using</code> statement. According to the book (p. 138),</p> <pre><code>using (StreamReader reader = File.OpenText("file.txt")) { ... } </code></pre> <p>is precisely equivalent to:</p> <pre><code>StreamReader reader = File.OpenText("file.txt"); try { ... } finally { if (reader != null) ((IDisposable)reader).Dispose(); } </code></pre> <p>Suppose, however, that this is true and that this code is executed in a separate thread. This thread is now aborted with <code>thread.Abort()</code>, so a <code>ThreadAbortException</code> is thrown and suppose the thread is exactly after initializing the reader and before entering the <code>try..finally</code> clause. This would mean that the reader is not disposed!</p> <p>A possible solution would be to code this way:</p> <pre><code>StreamReader reader = null; try { reader = File.OpenText("file.txt"); ... } finally { if (reader != null) ((IDisposable)reader).Dispose(); } </code></pre> <p>This would be abort-safe.</p> <p>Now for my questions:</p> <ol> <li>Are authors of the book right and the <code>using</code> statement is not abort-safe or are they wrong and it behaves like in my second solution?</li> <li>If <code>using</code> is equivalent to the first variant (not abort-safe), why does it check for <code>null</code> in <code>finally</code>?</li> <li>According to the book (p. 856), <code>ThreadAbortException</code> can be thrown anywhere in managed code. But maybe there are exceptions and the first variant is abort-safe after all?</li> </ol> <p><strong>EDIT:</strong> I know that using <code>thread.Abort()</code> is not considered good practice. My interest is purely theoretical: how does the <code>using</code> statement behave <strong>exactly</strong>?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload