Queue operation fully implemented; added small unit test for queue operation; some comment improvements in other code sections

git-svn-id: file:///srv/devel/repo-conversion/nusu@36 d2e56fa2-650e-0410-a79f-9358c0239efd
This commit is contained in:
Markus Ewald 2007-07-10 18:15:34 +00:00
parent 850db0cded
commit 4933604495
7 changed files with 357 additions and 33 deletions

View File

@ -170,6 +170,11 @@
<XNAUseContentPipeline>false</XNAUseContentPipeline> <XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>QueueOperation</Name> <Name>QueueOperation</Name>
</Compile> </Compile>
<Compile Include="Source\Scheduling\QueueOperation.Test.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>QueueOperation.Test</Name>
<DependentUpon>QueueOperation.cs</DependentUpon>
</Compile>
<Compile Include="Source\Scheduling\ThreadOperation.cs"> <Compile Include="Source\Scheduling\ThreadOperation.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline> <XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>ThreadOperation</Name> <Name>ThreadOperation</Name>

View File

@ -33,7 +33,9 @@ namespace Nuclex.Support.Scheduling {
/// <summary>Waits for the background operation to end</summary> /// <summary>Waits for the background operation to end</summary>
/// <remarks> /// <remarks>
/// Any exceptions raised in the background operation will be thrown /// Any exceptions raised in the background operation will be thrown
/// in this method. /// in this method. If you decide to override this method, you should
/// call End() first (and let any possible exception through to your
/// caller).
/// </remarks> /// </remarks>
public virtual void End() { public virtual void End() {
@ -83,7 +85,7 @@ namespace Nuclex.Support.Scheduling {
// We allow the caller to set the exception multiple times. While I certainly // We allow the caller to set the exception multiple times. While I certainly
// can't think of a scenario where this would happen, throwing an exception // can't think of a scenario where this would happen, throwing an exception
// in that case seems worse. The caller might just be executing an exception // in that case seems worse. The caller might just be executing an exception
// handling block and locking + throwing here could cause even more problems. // handling block and locking + throwing here could cause all kinds of problems.
this.occuredException = exception; this.occuredException = exception;
} }

View File

@ -0,0 +1,193 @@
#region CPL License
/*
Nuclex Framework
Copyright (C) 2002-2007 Nuclex Development Labs
This library is free software; you can redistribute it and/or
modify it under the terms of the IBM Common Public License as
published by the IBM Corporation; either version 1.0 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
IBM Common Public License for more details.
You should have received a copy of the IBM Common Public
License along with this library
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
#if UNITTEST
using NUnit.Framework;
using NMock2;
using Nuclex.Support.Tracking;
namespace Nuclex.Support.Scheduling {
/// <summary>Unit Test for the queue operation class</summary>
[TestFixture]
public class QueueOperationTest {
#region interface IQueueOperationSubscriber
/// <summary>Interface used to test the set progression.</summary>
public interface IQueueOperationSubscriber {
/// <summary>Called when the queue operations's progress changes</summary>
/// <param name="sender">Queue operation whose progress has changed</param>
/// <param name="e">Contains the new progress achieved</param>
void ProgressUpdated(object sender, ProgressUpdateEventArgs e);
/// <summary>Called when the queue operation has ended</summary>
/// <param name="sender">Queue operation that as ended</param>
/// <param name="e">Not used</param>
void Ended(object sender, EventArgs e);
}
#endregion // interface IQueueOperationSubscriber
#region class ProgressUpdateEventArgsMatcher
/// <summary>Compares two ProgressUpdateEventArgsInstances for NMock validation</summary>
private class ProgressUpdateEventArgsMatcher : Matcher {
/// <summary>Initializes a new ProgressUpdateEventArgsMatcher </summary>
/// <param name="expected">Expected progress update event arguments</param>
public ProgressUpdateEventArgsMatcher(ProgressUpdateEventArgs expected) {
this.expected = expected;
}
/// <summary>
/// Called by NMock to verfiy the ProgressUpdateEventArgs match the expected value
/// </summary>
/// <param name="actualAsObject">Actual value to compare to the expected value</param>
/// <returns>
/// True if the actual value matches the expected value; otherwise false
/// </returns>
public override bool Matches(object actualAsObject) {
ProgressUpdateEventArgs actual = (actualAsObject as ProgressUpdateEventArgs);
if(actual == null)
return false;
return (actual.Progress == this.expected.Progress);
}
/// <summary>Creates a string representation of the expected value</summary>
/// <param name="writer">Writer to write the string representation into</param>
public override void DescribeTo(TextWriter writer) {
writer.Write(this.expected.Progress.ToString());
}
/// <summary>Expected progress update event args value</summary>
private ProgressUpdateEventArgs expected;
}
#endregion // class ProgressUpdateEventArgsMatcher
#region class TestOperation
/// <summary>Progression used for testing in this unit test</summary>
private class TestOperation : Operation {
/// <summary>Begins executing the operation. Yeah, sure :)</summary>
public override void Begin() { }
/// <summary>Moves the operation into the ended state</summary>
public void SetEnded() {
SetEnded(null);
}
/// <summary>Moves the operation into the ended state with an exception</summary>
/// <param name="exception">Exception</param>
public void SetEnded(Exception exception) {
SetException(exception);
OnAsyncEnded();
}
/// <summary>Changes the testing progression's indicated progress</summary>
/// <param name="progress">
/// New progress to be reported by the testing progression
/// </param>
public void ChangeProgress(float progress) {
OnAsyncProgressUpdated(progress);
}
}
#endregion // class TestOperation
/// <summary>Initialization routine executed before each test is run</summary>
[SetUp]
public void Setup() {
this.mockery = new Mockery();
}
/// <summary>Validates that the queue executes operations sequentially</summary>
[Test]
public void TestSequentialExecution() {
TestOperation operation1 = new TestOperation();
TestOperation operation2 = new TestOperation();
QueueOperation<TestOperation> testQueueOperation =
new QueueOperation<TestOperation>(
new TestOperation[] { operation1, operation2 }
);
IQueueOperationSubscriber mockedSubscriber = mockSubscriber(testQueueOperation);
testQueueOperation.Begin();
Expect.Once.On(mockedSubscriber).
Method("ProgressUpdated").
With(
new Matcher[] {
new NMock2.Matchers.TypeMatcher(typeof(QueueOperation<TestOperation>)),
new ProgressUpdateEventArgsMatcher(new ProgressUpdateEventArgs(0.25f))
}
);
operation1.ChangeProgress(0.5f);
Expect.Once.On(mockedSubscriber).
Method("ProgressUpdated").
With(
new Matcher[] {
new NMock2.Matchers.TypeMatcher(typeof(QueueOperation<TestOperation>)),
new ProgressUpdateEventArgsMatcher(new ProgressUpdateEventArgs(0.5f))
}
);
operation1.SetEnded();
this.mockery.VerifyAllExpectationsHaveBeenMet();
}
/// <summary>Mocks a subscriber for the events of an operation</summary>
/// <param name="operation">Operation to mock an event subscriber for</param>
/// <returns>The mocked event subscriber</returns>
private IQueueOperationSubscriber mockSubscriber(Operation operation) {
IQueueOperationSubscriber mockedSubscriber =
this.mockery.NewMock<IQueueOperationSubscriber>();
operation.AsyncEnded += new EventHandler(mockedSubscriber.Ended);
operation.AsyncProgressUpdated +=
new EventHandler<ProgressUpdateEventArgs>(mockedSubscriber.ProgressUpdated);
return mockedSubscriber;
}
/// <summary>Mock object factory</summary>
private Mockery mockery;
}
} // namespace Nuclex.Support.Tracking
#endif // UNITTEST

View File

@ -32,36 +32,156 @@ namespace Nuclex.Support.Scheduling {
where OperationType : Operation { where OperationType : Operation {
/// <summary>Initializes a new queue operation</summary> /// <summary>Initializes a new queue operation</summary>
private QueueOperation() {
this.asyncOperationEndedDelegate = new EventHandler(asyncOperationEnded);
this.asyncOperationProgressUpdatedDelegate = new EventHandler<ProgressUpdateEventArgs>(
asyncOperationProgressUpdated
);
this.childs = new List<WeightedProgression<OperationType>>();
}
/// <summary>Initializes a new queue operation with default weights</summary>
/// <param name="childs">Child operations to execute in this operation</param> /// <param name="childs">Child operations to execute in this operation</param>
/// <remarks> /// <remarks>
/// All child operations will have a default weight of 1.0 /// All child operations will have a default weight of 1.0
/// </remarks> /// </remarks>
public QueueOperation(IEnumerable<OperationType> childs) { public QueueOperation(IEnumerable<OperationType> childs) : this() {
this.setProgression = new SetProgression<OperationType>(childs);
// Construct a WeightedProgression with the default weight for each
// progression and wrap it in an ObservedProgression
foreach(OperationType operation in childs)
this.childs.Add(new WeightedProgression<OperationType>(operation));
// Since all progressions have a weight of 1.0, the total weight is
// equal to the number of progressions in our list
this.totalWeight = (float)this.childs.Count;
} }
/// <summary>Initializes a new queue operation with custom weights</summary> /// <summary>Initializes a new queue operation with custom weights</summary>
/// <param name="childs">Child operations to execute in this operation</param> /// <param name="childs">Child operations to execute in this operation</param>
public QueueOperation(IEnumerable<WeightedProgression<OperationType>> childs) { public QueueOperation(IEnumerable<WeightedProgression<OperationType>> childs) : this() {
this.setProgression = new SetProgression<OperationType>(childs);
// Construct an ObservedProgression around each of the WeightedProgressions
foreach(WeightedProgression<OperationType> operation in childs) {
this.childs.Add(operation);
// Sum up the total weight
this.totalWeight += operation.Weight;
}
}
/// <summary>Provides access to the child operations of this queue</summary>
public IList<WeightedProgression<OperationType>> Childs {
get { return this.childs; }
} }
/// <summary>Launches the background operation</summary> /// <summary>Launches the background operation</summary>
public override void Begin() { public override void Begin() {
this.setProgression.AsyncProgressUpdated += beginCurrentOperation();
new EventHandler<ProgressUpdateEventArgs>(setProgressionProgressUpdated);
//this.setProgression.Childs[0].Progression.Begin();
} }
private void setProgressionProgressUpdated(object sender, ProgressUpdateEventArgs e) { /// <summary>Prepares the current operation and calls its Begin() method</summary>
throw new Exception("The method or operation is not implemented."); /// <remarks>
/// This subscribes the queue to the events of to the current operation
/// and launches the operation by calling its Begin() method.
/// </remarks>
private void beginCurrentOperation() {
OperationType operation = this.childs[this.currentOperationIndex].Progression;
operation.AsyncEnded += this.asyncOperationEndedDelegate;
operation.AsyncProgressUpdated += this.asyncOperationProgressUpdatedDelegate;
operation.Begin();
} }
/// <summary>SetProgression used internally to handle progress reports</summary> /// <summary>Disconnects from the current operation and calls its End() method</summary>
private volatile SetProgression<OperationType> setProgression; /// <remarks>
/// This unsubscribes the queue from the current operation's events, calls End()
/// on the operation and, if the operation didn't have an exception to report,
/// counts up the accumulated progress of the queue.
/// </remarks>
private void endCurrentOperation() {
OperationType operation = this.childs[this.currentOperationIndex].Progression;
// Disconnect from the operation's events
operation.AsyncEnded -= this.asyncOperationEndedDelegate;
operation.AsyncProgressUpdated -= this.asyncOperationProgressUpdatedDelegate;
try {
operation.End();
// Add the operations weight to the total amount of completed weight in the queue
this.completedWeight += this.childs[this.currentOperationIndex].Weight;
// Trigger another progress update
OnAsyncProgressUpdated(this.completedWeight / this.totalWeight);
}
catch(Exception exception) {
SetException(exception);
}
}
/// <summary>Called when the current executing operation ends</summary>
/// <param name="sender">Operation that ended</param>
/// <param name="e">Not used</param>
private void asyncOperationEnded(object sender, EventArgs e) {
// Unsubscribe from the current operation's events and update the
// accumulating progress counter
endCurrentOperation();
// Only jump to the next operation if no exception occured
if(OccuredException == null) {
++this.currentOperationIndex;
// Execute the next operation unless we reached the end of the queue
if(this.currentOperationIndex < this.childs.Count) {
beginCurrentOperation();
return;
}
}
// Either an exception has occured or we reached the end of the operation
// queue. In any case, we need to report that the operation is over.
OnAsyncEnded();
}
/// <summary>Called when currently executing operation makes progress</summary>
/// <param name="sender">Operation that has achieved progress</param>
/// <param name="e">Not used</param>
private void asyncOperationProgressUpdated(object sender, ProgressUpdateEventArgs e) {
// Determine the completed weight of the currently executing operation
float currentOperationCompletedWeight =
e.Progress * this.childs[this.currentOperationIndex].Weight;
// Build the total normalized amount of progress for the queue
float progress =
(this.completedWeight + currentOperationCompletedWeight) / this.totalWeight;
// Done, we can send the actual progress to any event subscribers
OnAsyncProgressUpdated(progress);
}
/// <summary>Delegate to the asyncOperationEnded() method</summary>
private EventHandler asyncOperationEndedDelegate;
/// <summary>Delegate to the asyncOperationProgressUpdated() method</summary>
private EventHandler<ProgressUpdateEventArgs> asyncOperationProgressUpdatedDelegate;
/// <summary>Operations being managed in the queue</summary>
private List<WeightedProgression<OperationType>> childs;
/// <summary>Summed weight of all operations in the queue</summary>
private float totalWeight;
/// <summary>Accumulated weight of the operations already completed</summary>
private float completedWeight;
/// <summary>Index of the operation currently executing</summary>
private int currentOperationIndex;
} }

View File

@ -34,7 +34,7 @@ namespace Nuclex.Support.Tracking {
/// This class does not implement the IProgression interface itself in /// This class does not implement the IProgression interface itself in
/// order to not violate the design principles of progressions which /// order to not violate the design principles of progressions which
/// guarantee that a progression will only finish once (whereas the /// guarantee that a progression will only finish once (whereas the
/// progression tracking might finish any number of times). /// progression tracker might 'finish' any number of times).
/// </para> /// </para>
/// </remarks> /// </remarks>
public class ProgressionTracker : IDisposable { public class ProgressionTracker : IDisposable {
@ -98,6 +98,10 @@ namespace Nuclex.Support.Tracking {
public void Dispose() { public void Dispose() {
lock(this.trackedProgressions) { lock(this.trackedProgressions) {
// Get rid of all progression we're tracking. This unsubscribes the
// observers from the events of the progressions and stops us from
// being kept alive and receiving any further events if some of the
// tracked progressions are still executing.
for(int index = 0; index < this.trackedProgressions.Count; ++index) for(int index = 0; index < this.trackedProgressions.Count; ++index)
this.trackedProgressions[index].Dispose(); this.trackedProgressions[index].Dispose();

View File

@ -180,20 +180,6 @@ namespace Nuclex.Support.Tracking {
this.mockery.VerifyAllExpectationsHaveBeenMet(); this.mockery.VerifyAllExpectationsHaveBeenMet();
} }
/// <summary>Mocks a subscriber for the events of a progression</summary>
/// <param name="progression">Progression to mock an event subscriber for</param>
/// <returns>The mocked event subscriber</returns>
private ISetProgressionSubscriber mockSubscriber(Progression progression) {
ISetProgressionSubscriber mockedSubscriber =
this.mockery.NewMock<ISetProgressionSubscriber>();
progression.AsyncEnded += new EventHandler(mockedSubscriber.Ended);
progression.AsyncProgressUpdated +=
new EventHandler<ProgressUpdateEventArgs>(mockedSubscriber.ProgressUpdated);
return mockedSubscriber;
}
/// <summary> /// <summary>
/// Validates that the ended event is triggered when the last progression ends /// Validates that the ended event is triggered when the last progression ends
/// </summary> /// </summary>
@ -220,6 +206,20 @@ namespace Nuclex.Support.Tracking {
this.mockery.VerifyAllExpectationsHaveBeenMet(); this.mockery.VerifyAllExpectationsHaveBeenMet();
} }
/// <summary>Mocks a subscriber for the events of a progression</summary>
/// <param name="progression">Progression to mock an event subscriber for</param>
/// <returns>The mocked event subscriber</returns>
private ISetProgressionSubscriber mockSubscriber(Progression progression) {
ISetProgressionSubscriber mockedSubscriber =
this.mockery.NewMock<ISetProgressionSubscriber>();
progression.AsyncEnded += new EventHandler(mockedSubscriber.Ended);
progression.AsyncProgressUpdated +=
new EventHandler<ProgressUpdateEventArgs>(mockedSubscriber.ProgressUpdated);
return mockedSubscriber;
}
/// <summary>Mock object factory</summary> /// <summary>Mock object factory</summary>
private Mockery mockery; private Mockery mockery;

View File

@ -167,7 +167,7 @@ namespace Nuclex.Support.Tracking {
/// WeightedProgression interface /// WeightedProgression interface
/// </summary> /// </summary>
private volatile WeightedProgressionWrapperCollection<ProgressionType> wrapper; private volatile WeightedProgressionWrapperCollection<ProgressionType> wrapper;
/// <summary>Summed weight of all progression in the set</summary> /// <summary>Summed weight of all progressions in the set</summary>
private float totalWeight; private float totalWeight;
} }