Lean  $LEAN_TAG$
ThreadSleepStrategy.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System.Threading;
17 
19 {
20  /// <summary>
21  /// Provides a CPU non-intensive means of waiting for more tokens to be available in <see cref="ITokenBucket"/>.
22  /// This strategy should be the most commonly used as it either sleeps or yields the currently executing thread,
23  /// allowing for other threads to execute while the current thread is blocked and waiting for new tokens to become
24  /// available in the bucket for consumption.
25  /// </summary>
27  {
28  /// <summary>
29  /// Gets an instance of <see cref="ISleepStrategy"/> that yields the current thread
30  /// </summary>
31  public static readonly ISleepStrategy Yielding = new ThreadSleepStrategy(0);
32 
33  /// <summary>
34  /// Gets an instance of <see cref="ISleepStrategy"/> that sleeps the current thread for
35  /// the specified number of milliseconds
36  /// </summary>
37  /// <param name="milliseconds">The duration of time to sleep, in milliseconds</param>
38  public static ISleepStrategy Sleeping(int milliseconds) => new ThreadSleepStrategy(milliseconds);
39 
40  private readonly int _milliseconds;
41 
42  /// <summary>
43  /// Initializes a new instance of the <see cref="ThreadSleepStrategy"/> using the specified
44  /// number of <paramref name="milliseconds"/> for each <see cref="Sleep"/> invocation.
45  /// </summary>
46  /// <param name="milliseconds">The duration of time to sleep, in milliseconds</param>
47  public ThreadSleepStrategy(int milliseconds)
48  {
49  _milliseconds = milliseconds;
50  }
51 
52  /// <summary>
53  /// Sleeps the current thread using the initialized number of milliseconds
54  /// </summary>
55  public void Sleep()
56  {
57  Thread.Sleep(_milliseconds);
58  }
59  }
60 }