SmartAPI
Open Source .NET RQL library for RedDot CMS / OpenText WSM Management Server
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Properties Pages
Wait.cs
Go to the documentation of this file.
1 ï»¿// SmartAPI - .Net programmatic access to RedDot servers
2 //
3 // Copyright (C) 2013 erminas GbR
4 //
5 // This program is free software: you can redistribute it and/or modify it
6 // under the terms of the GNU General Public License as published by the Free Software Foundation,
7 // either version 3 of the License, or (at your option) any later version.
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11 // See the GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License along with this program.
14 // If not, see <http://www.gnu.org/licenses/>.
15 
16 using System;
17 using System.Threading;
18 
19 namespace erminas.SmartAPI.Utils
20 {
21  public static class Wait
22  {
23  static Wait()
24  {
25  const int DEFAULT_PERIOD_IN_MS = 100;
26  DefaultRetryPeriod = new TimeSpan(0, 0, 0, 0, DEFAULT_PERIOD_IN_MS);
27  }
28 
29  public static TimeSpan DefaultRetryPeriod { get; set; }
30 
31  public static void For(Func<bool> pred, TimeSpan wait)
32  {
33  For(pred, wait, DefaultRetryPeriod);
34  }
35 
36  public static void For(Func<bool> pred, TimeSpan wait, TimeSpan retry)
37  {
38  if (retry > wait)
39  {
40  throw new ArgumentException("Retry period must not be greater than wait");
41  }
42  var tt = new TimeOutTracker(wait);
43  bool isSuccess;
44  var lastTry = DateTime.Now;
45  while (!(isSuccess = pred()) && !tt.HasTimedOut)
46  {
47  TimeSpan timeSpan = retry - (DateTime.Now - lastTry);
48  if (timeSpan.TotalMilliseconds > 0)
49  {
50  Thread.Sleep(timeSpan);
51  }
52  lastTry = DateTime.Now;
53  }
54  if (!isSuccess)
55  {
56  throw new TimeoutException(string.Format("timed out after waiting for {0}", wait));
57  }
58  }
59  }
60 }