我已经根据您的初始代码编写了这个简单的解决方案,但使用
ObservableCollection
,因此每次修改集合时都可以检查容量。
可以使用
NotifyCollectionChangedEventArgs
(修改类型、NewItems、OldItems等),只重新计算更改的内容,而不是每次迭代整个集合。
// simple object for the sake of this example
public class Task
{
public TimeSpan TimeToPerform;
}
public class ProductionQueue
{
public string? Name { get; set; }
/// <summary>
/// Maximum capacity of the queue. Keep it null for inifinte capacity.
/// </summary>
public TimeSpan? Capacity { get; set;}
public ObservableCollection<Task> Tasks = new ObservableCollection <Task>();
// ProductionQueue ctor
public ProductionQueue(TimeSpan? initialCapacity)
{
this.Capacity = initialCapacity;
// subscribe to know when the collection gets changed
this.Tasks.CollectionChanged += (s, e) => {
Console.WriteLine("collection changed");
this.checkCapacity();
};
}
private void checkCapacity()
{
var totalTime = TimeSpan.Zero;
foreach (var task in this.Tasks)
{
totalTime+= task.TimeToPerform;
}
if (totalTime > this.Capacity)
throw new Exception("queue time capacity exceeded");
}
}
}
下面是一个使用它的程序示例:
public static void Main(string[] args)
{
try
{
var PQ = new ProductionQueue(TimeSpan.FromHours(1));
PQ.Tasks.Add(new Task(){ TimeToPerform=TimeSpan.FromMinutes(40)});
PQ.Tasks.Add(new Task(){ TimeToPerform=TimeSpan.FromMinutes(30)});
Console.WriteLine("Tasks added without problem");
}
catch(Exception e)
{
Console.WriteLine("Exception occured: "+e.Message);
}
}
控制台输出:
collection changed
collection changed
Exception occured: queue time capacity exceeded