mirror of
https://github.com/ICDSystems/ICD.Common.Utils.git
synced 2026-02-14 12:15:05 +00:00
Adding method for waiting, with timeout, until a condition is true
This commit is contained in:
@@ -4,8 +4,25 @@ using NUnit.Framework;
|
||||
namespace ICD.Common.Utils.Tests
|
||||
{
|
||||
[TestFixture]
|
||||
public sealed class ThreadingUtilsTest
|
||||
{
|
||||
public sealed class ThreadingUtilsTest
|
||||
{
|
||||
[Test]
|
||||
public static void WaitTest()
|
||||
{
|
||||
Assert.IsFalse(ThreadingUtils.Wait(() => false, 100));
|
||||
Assert.IsTrue(ThreadingUtils.Wait(() => true, 100));
|
||||
|
||||
bool complete = false;
|
||||
|
||||
ThreadingUtils.SafeInvoke(() =>
|
||||
{
|
||||
ThreadingUtils.Sleep(50);
|
||||
complete = true;
|
||||
});
|
||||
|
||||
Assert.IsTrue(ThreadingUtils.Wait(() => complete, 100));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Sleep()
|
||||
{
|
||||
@@ -20,7 +37,11 @@ namespace ICD.Common.Utils.Tests
|
||||
public void SafeInvokeTest()
|
||||
{
|
||||
bool result = false;
|
||||
ThreadingUtils.SafeInvoke(() => { ThreadingUtils.Sleep(100); result = true; });
|
||||
ThreadingUtils.SafeInvoke(() =>
|
||||
{
|
||||
ThreadingUtils.Sleep(100);
|
||||
result = true;
|
||||
});
|
||||
|
||||
Assert.IsFalse(result);
|
||||
ThreadingUtils.Sleep(1000);
|
||||
@@ -31,7 +52,11 @@ namespace ICD.Common.Utils.Tests
|
||||
public void SafeInvokeParamTest()
|
||||
{
|
||||
bool result = false;
|
||||
ThreadingUtils.SafeInvoke(p => { ThreadingUtils.Sleep(100); result = p; }, true);
|
||||
ThreadingUtils.SafeInvoke(p =>
|
||||
{
|
||||
ThreadingUtils.Sleep(100);
|
||||
result = p;
|
||||
}, true);
|
||||
|
||||
Assert.IsFalse(result);
|
||||
ThreadingUtils.Sleep(1000);
|
||||
|
||||
@@ -12,6 +12,28 @@ namespace ICD.Common.Utils
|
||||
{
|
||||
public static class ThreadingUtils
|
||||
{
|
||||
/// <summary>
|
||||
/// Wait until the given condition is true.
|
||||
/// </summary>
|
||||
/// <param name="condition"></param>
|
||||
/// <param name="timeout"></param>
|
||||
/// <returns></returns>
|
||||
public static bool Wait(Func<bool> condition, long timeout)
|
||||
{
|
||||
if (condition == null)
|
||||
throw new ArgumentNullException("condition");
|
||||
|
||||
DateTime end = IcdEnvironment.GetLocalTime().AddMilliseconds(timeout);
|
||||
|
||||
while (!condition())
|
||||
{
|
||||
if (IcdEnvironment.GetLocalTime() >= end)
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Puts the current thread to sleep for the given amount of time.
|
||||
/// </summary>
|
||||
|
||||
Reference in New Issue
Block a user