0

I have a method that gets an object as argument. The method blocks the thread using a ManualResetEventSlim. The object has an event that is fired if the object's state changes. The method will then check the new state of the object and if the new State is StateX the ManualResetEventSlim is set and the thread can continue:

internal class StateXAwaiter
{
    private readonly ManualResetEventSlim manualResetEventSlim;

    public StateXAwaiter(ManualResetEventSlim manualResetEventSlim)
    {
        this.manualResetEventSlim = manualResetEventSlim;
    }

    public void WaitForStateX(IStatefullObject statefullObject)
    {
        this.manualResetEventSlim.Reset();

        stateFullObject.StateChanged += this.OnStateChanged;

        this.manualResetEventSlim.Wait();

        stateFullObject.StateChanged -= this.OnStateChanged;
    }

    private void OnStateChanged(object sender, State newState)
    {
        if (newState == State.StateX)
        {
            this.manualResetEventSlim.Set();
        }
    }
}

public interface IStatefullObject
{
    public event EventHandler<State> StateChanged;
}

public enum State
{
    StateX,
    StateY
}

I would like write a test that fires the event and checks if the thread continues. I imagine the method call should occur inside a Task and then the event should be fired in the test thread. But the problem is if the event is fired before it is subscribed inside the method. In that case the event will be unnoticed and the thread keeps waiting forever. How can i make sure the event is fired only when the thread is actually waiting at the ManualResetEventSlim?

Patb
  • 31
  • 3

0 Answers0