Skip to main content

Self-changing flag pattern and standard implementation [Resolved]

I'm working on a piece of code processing loads of messages and passing these to another service. This process may fail, resulting in a faulted reference to the service. Whenever a failure occurs, the message accepting code should continue to accept messages, but just discard those for a predefined period of time after which a new service reference is constructed. I've implemented the following construct;

class MessageProcesser
{
    private CircuitBreak _circuitBreak = new CircuitBreak();

    public async Task ProcessMessageAsync(string message)
    {
        if (_circuitBreak.IsOpen)
        {
            try
            {
                await DoSomethingAsync(message);
            }
            catch (Exception)
            {
                _circuitBreak = new CircuitBreak(5000);
            }
        }
    }
}

With a self-opening 'blocker' as;

class CircuitBreak
{
    private readonly DateTimeOffset _willOpenAfter;

    public bool IsOpen { get { return DateTimeOffset.UtcNow > _willOpenAfter; } }

    public CircuitBreak(double milliSeconds = 0.0d)
    {
        _willOpenAfter = DateTimeOffset.UtcNow.AddMilliseconds(milliSeconds);
    }
}

When I look at all the synchronization classes in the .NET framework (Semaphore, Barrier, etc) I'm expecting some class that suits my needs should also be somewhere in the framework. Is there a name for a pattern like mine and is there already a implementation of a self-changing flag in the .NET framework?


Asked March 20, 2017
Posted Under: Programming
55 views
1 Answers

How about something like this? Use a timer to set an event, encapsulate in a generic.

class TemporaryValue<T>
{
    volatile private T _value;

    public TemporaryValue(T initialValue, int millisecondWait, T nextValue)
    {
        _value = initialValue;
        var timer = new System.Timers.Timer
        {
            Interval = milliseconds,
            AutoReset = false,
            Elapsed += () => { _value = nextValue; timer.Dispose(); }
        }.Start();
    }

    public Value
    {
        get { return _value; }
    }

    public static implicit operator T(TemporaryValue<T> tv)
    {
        return tv.Value;
    }
}

Because of the implicit operator, you can assign to a bool.

bool flag = new TemporaryValue<bool>(true, 10000, false);

Answered March 20, 2017
 
Volatile tells the compiler that the value might be updated from outside the current thread, which will cause it to disable certain optimizations, e.g. using a CPU register for temporary storage. – John Wu 9 hours ago
 CanDoerz  4 months ago
 
Thanks, I really like your solution. Although I suppose this means that answer to the actual question would be: 'No, the .NET framework doesn't provide similar functionality'. Also, could you elaborate why you use the volatile keyword here? – Michiel T 9 hours ago
 CanDoerz  4 months ago
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA