Dispose of objects in reverse order of creation?

I encounter a recurring problem in the code that I write: a change in some global value (I use the registry value as an example), and then try to return the changes to their original state.

I thought I would try to use IDisposable to solve this problem. Upon creation, the object will read the registry value, save it locally and then modify it. When it is destroyed, it will return the setting. It will be used something like this:

using(RegistryModification mod = new RegistryModification("HKCR\SomeValue", 42))
{
    // reg value now modified to 42, do stuff
} // Object gets disposed, which contains code to revert back the setting

It should work fine, if only one modification is made. But if several modifications are made, or the calling object does not create objects with a "using" construct, I see problems.

public void Foo()
{
    // assume HKCR\SomeValue starts as '13'

    // First object reads HKCR\SomeValue and stores '13', then modifies to 42
    RegistryModification mod1 = new RegistryModification("HKCR\SomeValue", 42); 

    // Next object reads HKCR\SomeValue and stores '42', then modifies to 12
    RegistryModification mod2 = new RegistryModification("HKCR\SomeValue", 12);

}
// objects are destroyed. But if mod1 was destroyed first, followed by mod2,
// the reg value is set to 42 and not 13. Bad!!!

, . , , , .

- ? , .

- ? , IDisposable, .

+3
4

IDisposable , , . Dispose() , , ( , ..)

:

public void Foo(SomeObjectType theObject)
{
    int initialValue = theObject.SomeProperty;
    theObject.SomeProperty = 25;
    Console.Out.WriteLine("Property is:" + theObject.SomeProperty);

    // reset object.
    theObject.SomeProperty = initialValue;
    Console.Out.WriteLine("Property oringinal value is:" + theObject.SomeProperty);
}

, , , , , , , .

Dispose() , , , . , , dispose, , .net Dispose()

, , , , . , , .

, , (, , GDI). , . , , , Dispose , , , dispose. , , . , , - reset ( ). , .

, , , . , (, ) , , , .

+4

, System.Collections.Generic.Stack<T>. , "" .

http://msdn.microsoft.com/en-us/library/3278tedw.aspx

+1

factory RegistryModification ( RegistryModifcation, , , , ) RegistryModification. , . (, , ).

, , , , .

0

: " - , , ":

// Pattern #1

void FancyDoSomething(MethodInvoker ThingToDo)
{
  try
  {
    PrepareToDoSomething();
    ThingToDo.Invoke(); // The ".Invoke" is optional; the parens aren't.
  }
  finally
  {
    Cleanup();
  }
}

void myCode(void)
{
  FancyDoSomething( () => {Stuff to do goes here});
}

// Pattern #2:

// Define an ActionWrapper so its constructor prepares to do something
// and its Dispose method does the required cleanup.  Then...

void myCode(void)
{
  using(var wrap = new ActionWrapper())
  {
    Stuff to do goes here
  }
}

№2 , , . , IEnumerator<T> , . - , , .

, . , , , , - .

, , Disposing , , , . " ", , - , Dispose d ( , , , , , - ).

0

All Articles