Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it abusive to use IDisposable and "using" as a means for getting "scoped behavior" for exception safety?
    primarykey
    data
    text
    <p>Something I often used back in C++ was letting a class <code>A</code> handle a state entry and exit condition for another class <code>B</code>, via the <code>A</code> constructor and destructor, to make sure that if something in that scope threw an exception, then B would have a known state when the scope was exited. This isn't pure RAII as far as the acronym goes, but it's an established pattern nevertheless.</p> <p>In C#, I often want to do</p> <pre><code>class FrobbleManager { ... private void FiddleTheFrobble() { this.Frobble.Unlock(); Foo(); // Can throw this.Frobble.Fiddle(); // Can throw Bar(); // Can throw this.Frobble.Lock(); } } </code></pre> <p>Which needs to be done like this</p> <pre><code>private void FiddleTheFrobble() { this.Frobble.Unlock(); try { Foo(); // Can throw this.Frobble.Fiddle(); // Can throw Bar(); // Can throw } finally { this.Frobble.Lock(); } } </code></pre> <p>if I want to guarantee the <code>Frobble</code> state when <code>FiddleTheFrobble</code> returns. The code would be nicer with</p> <pre><code>private void FiddleTheFrobble() { using (var janitor = new FrobbleJanitor(this.Frobble)) { Foo(); // Can throw this.Frobble.Fiddle(); // Can throw Bar(); // Can throw } } </code></pre> <p>where <code>FrobbleJanitor</code> looks <strong>roughly</strong> like</p> <pre><code>class FrobbleJanitor : IDisposable { private Frobble frobble; public FrobbleJanitor(Frobble frobble) { this.frobble = frobble; this.frobble.Unlock(); } public void Dispose() { this.frobble.Lock(); } } </code></pre> <p>And that's how I want to do it. Now reality catches up, since what I <strong>want</strong> to use <strong>requires</strong> that the <code>FrobbleJanitor</code> is used <strong>with</strong> <code>using</code>. I could consider this a code review issue, but something is nagging me.</p> <p><strong>Question:</strong> Would the above be considered as abusive use of <code>using</code> and <code>IDisposable</code>?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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