.NET implementation of an active object template

I am looking for implementations of an active object template, but not so many so far. Here is what I came up with:

You need something a little more active. Preferred for .NET Version <= 3.5.

+3
source share
4 answers

Simple implementation using 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());
    }
}

InvokeAsyncnot thread safe, use lock (_lastTask) lastTask = ...;if you need it.

+2
source

Adding the Quiet Answer to Anton, there is a version of System.Threading.Tasks.Task for .NET 3.5, available as part of Reactive Extensions . Please note that this version does not have official Microsoft support.

0
source

Source: https://habr.com/ru/post/1790964/


All Articles