๐Ÿ“ฆ about ๐Ÿงป posts
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
}
question_answer
Dan Bugglin
Monday, November 6, 2023
I did something like this in a project I'm working on, though I put an event instead of a callback on the class. Callback is definitely more readable (I'm not touching my existing code though, it works fine!)

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

An error has occurred. This application may no longer respond until reloaded. Reload ๐Ÿ—™