Lean  $LEAN_TAG$
WorkItem.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 
17 using System;
18 using System.Runtime.CompilerServices;
19 
21 {
22  /// <summary>
23  /// Class to represent a work item
24  /// </summary>
25  public class WorkItem
26  {
27  /// <summary>
28  /// Function to determine weight of item
29  /// </summary>
30  private Func<int> _weightFunc;
31 
32  /// <summary>
33  /// The current weight
34  /// </summary>
35  public int Weight { get; private set; }
36 
37  /// <summary>
38  /// The work function to execute
39  /// </summary>
40  public Func<int, bool> Work { get; }
41 
42  /// <summary>
43  /// Creates a new instance
44  /// </summary>
45  /// <param name="work">The work function, takes an int, the amount of work to do
46  /// and returns a bool, false if this work item is finished</param>
47  /// <param name="weightFunc">The function used to determine the current weight</param>
48  public WorkItem(Func<int, bool> work, Func<int> weightFunc)
49  {
50  Work = work;
51  _weightFunc = weightFunc;
52  }
53 
54  /// <summary>
55  /// Updates the weight of this work item
56  /// </summary>
57  [MethodImpl(MethodImplOptions.AggressiveInlining)]
58  public int UpdateWeight()
59  {
60  Weight = _weightFunc();
61  return Weight;
62  }
63 
64  /// <summary>
65  /// Compares two work items based on their weights
66  /// </summary>
67  public static int Compare(WorkItem obj, WorkItem other)
68  {
69  if (ReferenceEquals(obj, other))
70  {
71  return 0;
72  }
73  // By definition, any object compares greater than null
74  if (ReferenceEquals(obj, null))
75  {
76  return -1;
77  }
78  if (ReferenceEquals(null, other))
79  {
80  return 1;
81  }
82 
83  return other.Weight.CompareTo(obj.Weight);
84  }
85  }
86 }