Skip to content

Instantly share code, notes, and snippets.

@redsquare
Forked from jmarnold/Wait.cs
Created Nov 21, 2012
Embed
What would you like to do?
Wait
public static class Wait
{
public static bool ForExpectedValue<T>(T expectation, Func<T> source, int millisecondPolling = 500, int timeoutInMilliseconds = 5000)
{
var matched = Wait.Until(() => expectation.Equals(source()), millisecondPolling, timeoutInMilliseconds).WasSatisfied;
StoryTellerAssert.Fail(!matched, () => "Expected {0}, but was {1}".ToFormat(expectation, source()));
return true;
}
public static Satisfied Until(Func<bool> condition, int millisecondPolling = 500, int timeoutInMilliseconds = 5000)
{
if (condition()) return new Satisfied(true);
var returnValue = false;
var clock = new Stopwatch();
clock.Start();
var reset = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(o =>
{
while (true)
{
try
{
if (condition())
{
returnValue = true;
break;
}
}
catch (Exception)
{
// Yeah, that's right. I wanna swallow these exceptions
}
Thread.Sleep(100);
}
reset.Set();
});
reset.WaitOne(timeoutInMilliseconds);
return new Satisfied(returnValue);
}
public class Satisfied
{
private readonly bool _returnValue;
public Satisfied(bool returnValue)
{
_returnValue = returnValue;
}
public bool WasSatisfied
{
get
{
return _returnValue;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment