Skip to content

Instantly share code, notes, and snippets.

@jmarnold
Created November 20, 2012 15:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jmarnold/4118678 to your computer and use it in GitHub Desktop.
Save jmarnold/4118678 to your computer and use it in GitHub Desktop.
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