Disposable Action
I like doing scopes in c#. I like that pattern. I always used to write an IDisposable class for each scope.. but then I saw this pattern.
public struct DisposeAction : IDisposable
{
public Action Action;
public DisposeAction( Action action )
{
Action = action;
}
public void Dispose()
{
Action?.Invoke();
Action = null;
}
public static IDisposable Create( Action action )
{
return new DisposeAction( action );
}
}So how this works, is you can do something like this..
public partial World
{
public IDisposable Push()
{
var previous = CurrentWorld;
CurrentWorld = this;
return DisposeAction.Create( () =>
{
CurrentWorld = previous
} );
}
}
Then in your normal every day code, you can scope push shit.
using ( myWorld.Push() )
{
// Do stuff using CurrentWorld
using ( childWorld.Push() )
{
// Do stuff using CurrentWorld
}
// Do stuff using CurrentWorld
}

I used it to make a queueing system. Like the lock keyword but it guarantees everything runs in the order it was queued up, and I can destroy the whole queue if it becomes irrelevant.
Add a Comment