Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET implementation of the active object pattern

I'm looking for implementations of the active object pattern, but haven't for much so far. This is what I came up with:

  • http://geekswithblogs.net/dbose/archive/2009/10/17/c-activeobject-runnable.aspx

Need something a little bit more involved. Preferably for .NET Version <= 3.5.

like image 938
Jan Deinhard Avatar asked Nov 08 '25 01:11

Jan Deinhard


1 Answers

The simple implementation that uses System.Threading.Tasks.Task

class ActiveObject : IDisposable
{
    private Task _lastTask = Task.Factory.StartNew(() => { });

    public void Dispose()
    {
        if (_lastTask == null)
            return;

        _lastTask.Wait();
        _lastTask = null;
    }

    public void InvokeAsync(Action action)
    {
        if (_lastTask == null)
            throw new ObjectDisposedException(GetType().FullName);

        _lastTask = _lastTask.ContinueWith(t => action());
    }
}

InvokeAsync isn't thread-safe, use lock (_lastTask) lastTask = ...; if you need it.

like image 74
Abyx Avatar answered Nov 09 '25 21:11

Abyx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!