Began implementing the ProgressionTracker

git-svn-id: file:///srv/devel/repo-conversion/nusu@34 d2e56fa2-650e-0410-a79f-9358c0239efd
This commit is contained in:
Markus Ewald 2007-07-05 20:02:02 +00:00
parent 46c0ac68af
commit 344e5fac53
11 changed files with 363 additions and 66 deletions

View File

@ -166,6 +166,18 @@
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>AbortedException</Name>
</Compile>
<Compile Include="Source\Scheduling\QueueOperation.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>QueueOperation</Name>
</Compile>
<Compile Include="Source\Scheduling\ThreadOperation.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>ThreadOperation</Name>
</Compile>
<Compile Include="Source\Scheduling\WeightedRequirableOperation.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>WeightedRequirableOperation</Name>
</Compile>
<Compile Include="Source\Serialization\BinarySerializer.Test.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>BinarySerializer.Test</Name>
@ -203,9 +215,13 @@
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>SpatialIndex2</Name>
</Compile>
<Compile Include="Source\Tracking\Internal\ObservedProgression.cs">
<Compile Include="Source\Tracking\IdleStateEventArgs.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>ObservedProgression</Name>
<Name>IdleStateEventArgs</Name>
</Compile>
<Compile Include="Source\Tracking\Internal\ObservedWeightedProgression.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>ObservedWeightedProgression</Name>
</Compile>
<Compile Include="Source\Tracking\ProgressionTracker.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
@ -227,9 +243,9 @@
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>ProgressUpdateEventArgs</Name>
</Compile>
<Compile Include="Source\Scheduling\ThreadedMethodOperation.cs">
<Compile Include="Source\Scheduling\ThreadCallbackOperation.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>
<Name>ThreadedMethodOperation</Name>
<Name>ThreadCallbackOperation</Name>
</Compile>
<Compile Include="Source\Tracking\SetProgression.Test.cs">
<XNAUseContentPipeline>false</XNAUseContentPipeline>

View File

@ -212,7 +212,7 @@ namespace Nuclex.Support.Licensing {
private static readonly string codeTable =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/// <summary>Helper array with the powers of two</summary>
/// <summary>Helper array containing the precalculated powers of two</summary>
private static readonly uint[,] powersOfTwo = new uint[32, 2] {
{ 0, 1 }, { 0, 2 }, { 0, 4 }, { 0, 8 },
{ 0, 16 }, { 0, 32 }, { 0, 64 }, { 0, 128 },

View File

@ -27,12 +27,6 @@ namespace Nuclex.Support.Scheduling {
/// <summary>Base class for observable operations running in the background</summary>
public abstract class Operation : Progression {
/// <summary>Executes the operation synchronously</summary>
public virtual void Execute() {
Begin();
End();
}
/// <summary>Launches the background operation</summary>
public abstract void Begin();
@ -55,10 +49,12 @@ namespace Nuclex.Support.Scheduling {
} else {
error = true;
}
}
} // lock
} else {
error = true;
}
if(error)
throw new InvalidOperationException("End() has already been called");
// If the progression itself hasn't ended yet, block the caller until it has.
if(!Ended)
@ -75,7 +71,25 @@ namespace Nuclex.Support.Scheduling {
/// If this field is null, it is assumed that no exception has occured
/// in the background process. When it is set, the End() method will
/// </remarks>
protected Exception occuredException;
public Exception OccuredException {
get { return this.occuredException; }
}
/// <summary>Sets the exception to raise to the caller of the End() method</summary>
/// <param name="exception">Exception to raise to the caller of the End() method</param>
protected void SetException(Exception exception) {
// 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
// in that case seems worse. The caller might just be executing an exception
// handling block and locking the operation instance could cause all even
// more problems.
this.occuredException = exception;
}
/// <summary>Exception that occured while the operation was executing</summary>
private volatile Exception occuredException;
/// <summary>Whether the End() method has been called already</summary>
private volatile bool endCalled;

View File

@ -0,0 +1,68 @@
#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 Nuclex.Support.Tracking;
namespace Nuclex.Support.Scheduling {
/// <summary>Operation that sequentially executes a series of operations</summary>
/// <typeparam name="OperationType">
/// Type of the child operations the QueueOperation will contain
/// </typeparam>
public class QueueOperation<OperationType> : Operation
where OperationType : Operation {
/// <summary>Initializes a new queue operation</summary>
/// <param name="childs">Child operations to execute in this operation</param>
/// <remarks>
/// All child operations will have a default weight of 1.0
/// </remarks>
public QueueOperation(IEnumerable<OperationType> childs) {
this.setProgression = new SetProgression<OperationType>(childs);
}
/// <summary>Initializes a new queue operation with custom weights</summary>
/// <param name="childs">Child operations to execute in this operation</param>
public QueueOperation(IEnumerable<WeightedProgression<OperationType>> childs) {
this.setProgression = new SetProgression<OperationType>(childs);
}
/// <summary>Launches the background operation</summary>
public override void Begin() {
this.setProgression.AsyncProgressUpdated +=
new EventHandler<ProgressUpdateEventArgs>(setProgressionProgressUpdated);
//this.setProgression.Childs[0].Progression.Begin();
}
private void setProgressionProgressUpdated(object sender, ProgressUpdateEventArgs e) {
throw new Exception("The method or operation is not implemented.");
}
/// <summary>SetProgression used internally to handle progress reports</summary>
private volatile SetProgression<OperationType> setProgression;
}
} // namespace Nuclex.Support.Scheduling

View File

@ -24,7 +24,7 @@ using System.Threading;
namespace Nuclex.Support.Scheduling {
/// <summary>Operation that executes a method in a background thread</summary>
public class ThreadedMethodOperation : Operation {
public class ThreadCallbackOperation : ThreadOperation {
/// <summary>
/// Initializes a new threaded method operation for a parameterless method
@ -33,7 +33,7 @@ namespace Nuclex.Support.Scheduling {
/// <remarks>
/// Uses a ThreadPool thread to execute the method in
/// </remarks>
public ThreadedMethodOperation(ThreadStart method)
public ThreadCallbackOperation(ThreadStart method)
: this(method, true) { }
/// <summary>
@ -46,35 +46,20 @@ namespace Nuclex.Support.Scheduling {
/// that the method will be executed immediately but has an impact on
/// performance since the creation of new threads is not a cheap operation.
/// </remarks>
public ThreadedMethodOperation(ThreadStart method, bool useThreadPool) {
if(useThreadPool) {
ThreadPool.QueueUserWorkItem(callMethod, method);
} else {
Thread thread = new Thread(callMethod);
thread.Name = "Nuclex.Support.Scheduling.ThreadedMethodOperation thread";
thread.IsBackground = true;
thread.Start(method);
}
public ThreadCallbackOperation(ThreadStart method, bool useThreadPool)
: base(useThreadPool) {
this.method = method;
}
/// <summary>Invokes the delegate passed as an argument</summary>
/// <param name="method">ThreadStart-comaptible Delegate to invoke</param>
private void callMethod(object method) {
#if PROGRESSION_STARTABLE
AsyncStarted();
#endif
try {
((ThreadStart)method)();
}
catch(Exception exception) {
this.occuredException = exception;
}
finally {
AsyncEnded();
}
/// <summary>Executes the thread callback in the background thread</summary>
protected override void Execute() {
this.method();
}
/// <summary>Method to be invoked in a background thread</summary>
private ThreadStart method;
}
} // namespace Nuclex.Support.Scheduling

View File

@ -0,0 +1,88 @@
#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.Threading;
namespace Nuclex.Support.Scheduling {
/// <summary>Operation that executes a method in a background thread</summary>
public abstract class ThreadOperation : Operation {
/// <summary>
/// Initializes a new threaded operation
/// </summary>
/// <remarks>
/// Uses a ThreadPool thread to execute the method in
/// </remarks>
public ThreadOperation() : this(true) { }
/// <summary>
/// Initializes a new threaded operation
/// </summary>
/// <param name="useThreadPool">Whether tos use a ThreadPool thread</param>
/// <remarks>
/// If useThreadPool is false, a new thread will be created. This guarantees
/// that the method will be executed immediately but has an impact on
/// performance since the creation of new threads is not a cheap operation.
/// </remarks>
public ThreadOperation(bool useThreadPool) {
this.useThreadPool = useThreadPool;
}
/// <summary>Launches the background operation</summary>
public override void Begin() {
if(useThreadPool) {
ThreadPool.QueueUserWorkItem(callMethod);
} else {
Thread thread = new Thread(callMethod);
thread.Name = "Nuclex.Support.Scheduling.ThreadOperation";
thread.IsBackground = true;
thread.Start();
}
}
/// <summary>Contains the payload to be executed in the background thread</summary>
protected abstract void Execute();
/// <summary>Invokes the delegate passed as an argument</summary>
/// <param name="state">Not used</param>
private void callMethod(object state) {
#if PROGRESSION_STARTABLE
OnAsyncStarted();
#endif
try {
Execute();
}
catch(Exception exception) {
SetException(exception);
}
finally {
OnAsyncEnded();
}
}
/// <summary>Whether to use the ThreadPool for obtaining a background thread</summary>
private bool useThreadPool;
}
} // namespace Nuclex.Support.Scheduling

View File

@ -0,0 +1,45 @@
#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.Text;
namespace Nuclex.Support.Tracking {
/// <summary>Event arguments for an idle state change notification</summary>
public class IdleStateEventArgs : EventArgs {
/// <summary>Initializes the idle state change notification</summary>
/// <param name="idle">The new idle state</param>
public IdleStateEventArgs(bool idle) {
this.idle = idle;
}
/// <summary>Current idle state</summary>
public bool Idle {
get { return this.idle; }
}
/// <summary>Current idle state</summary>
private bool idle;
}
} // namespace Nuclex.Support.Tracking

View File

@ -27,7 +27,7 @@ namespace Nuclex.Support.Tracking {
/// <typeparam name="ProgressionType">
/// Type of the progression that is being observed
/// </typeparam>
internal class ObservedProgression<ProgressionType> : IDisposable
internal class ObservedWeightedProgression<ProgressionType> : IDisposable
where ProgressionType : Progression {
/// <summary>Delegate for reporting progress updates</summary>
@ -41,7 +41,7 @@ namespace Nuclex.Support.Tracking {
/// <param name="endedCallback">
/// Callback to invoke when the progression has ended
/// </param>
internal ObservedProgression(
internal ObservedWeightedProgression(
WeightedProgression<ProgressionType> weightedProgression,
ReportDelegate progressUpdateCallback,
ReportDelegate endedCallback

View File

@ -48,14 +48,14 @@ namespace Nuclex.Support.Tracking {
/// </remarks>
internal class WeightedProgressionWrapperCollection<ProgressionType> :
TransformingReadOnlyCollection<
ObservedProgression<ProgressionType>, WeightedProgression<ProgressionType>
ObservedWeightedProgression<ProgressionType>, WeightedProgression<ProgressionType>
>
where ProgressionType : Progression {
/// <summary>Initializes a new weighted progression collection wrapper</summary>
/// <param name="items">Items to be exposed as weighted progressions</param>
internal WeightedProgressionWrapperCollection(
IList<ObservedProgression<ProgressionType>> items
IList<ObservedWeightedProgression<ProgressionType>> items
)
: base(items) { }
@ -69,7 +69,7 @@ namespace Nuclex.Support.Tracking {
/// not cache otherwise store the transformed items.
/// </remarks>
protected override WeightedProgression<ProgressionType> Transform(
ObservedProgression<ProgressionType> item
ObservedWeightedProgression<ProgressionType> item
) {
return item.WeightedProgression;
}

View File

@ -22,15 +22,97 @@ using System.Collections.Generic;
using System.Text;
namespace Nuclex.Support.Tracking {
/*
public abstract class ProgressionTracker {
public void Track() {}
/// <summary>Helps tracking the progress of one or more progressions</summary>
/// <remarks>
/// <para>
/// This is useful if you want to display a progress bar for multiple
/// progressions but can not guarantee that no additional progressions
/// will appear inmidst of execution.
/// </para>
/// <para>
/// This class does not implement the IProgression interface itself in
/// order to not violate the design principles of progressions which
/// guarantee that a progression will only finish once (whereas the
/// progression tracking might finish any number of times).
/// </para>
/// </remarks>
public class ProgressionTracker : IDisposable {
protected virtual void OnStartTracking();
protected virtual void OnEndTracking();
protected virtual void OnProgressUpdated();
/// <summary>Triggered when the idle state of the tracker changes</summary>
/// <remarks>
/// The tracker is idle when no progressions are being tracked in it. If you're
/// using this class to feed a progress bar, this would be the event to use for
/// showing or hiding the progress bar. The tracker starts off as idle because,
/// upon construction, its list of progressions will be empty.
/// </remarks>
public event EventHandler<IdleStateEventArgs> AsyncIdleStateChanged;
/// <summary>Triggered when the total progress has changed</summary>
public event EventHandler<ProgressUpdateEventArgs> AsyncProgressUpdated;
/// <summary>Immediately releases all resources owned by the instance</summary>
public void Dispose() {
// TODO: Untrack all
}
/// <summary>Begins tracking the specified progression</summary>
/// <param name="progression">Progression to be tracked</param>
public void Track(Progression progression) {
Track(progression, 1.0f);
}
/// <summary>Begins tracking the specified progression</summary>
/// <param name="progression">Progression to be tracked</param>
/// <param name="weight">Weight to assign to this progression</param>
public void Track(Progression progression, float weight) {
this.trackedProgressions.Add(
new WeightedProgression<Progression>(progression, weight)
);
this.totalWeight += weight;
recalculateProgress();
}
/// <summary>Stops tracking the specified progression</summary>
/// <param name="progression">Progression to stop tracking of</param>
public void Untrack(Progression progression) { }
/// <summary>Fires the AsyncIdleStateChanged event</summary>
/// <param name="idle">New idle state to report</param>
protected virtual void OnAsyncIdleStateChanged(bool idle) {
EventHandler<IdleStateEventArgs> copy = AsyncIdleStateChanged;
if(copy != null)
copy(this, new IdleStateEventArgs(idle));
}
/// <summary>Fires the AsyncProgressUpdated event</summary>
/// <param name="progress">New progress to report</param>
protected virtual void OnAsyncProgressUpdated(float progress) {
EventHandler<ProgressUpdateEventArgs> copy = AsyncProgressUpdated;
if(copy != null)
copy(this, new ProgressUpdateEventArgs(progress));
}
/// <summary>Recalculates the total progress of the tracker</summary>
private void recalculateProgress() {
float totalProgress;
for(int index = 0; index < trackedProgressions.Count; ++index) {
float weight = this.trackedProgressions[index].WeightedProgression;
totalProgress = this.trackedProgressions[index].Progress * weight;
}
totalProgress /= this.totalWeight;
//OnAsyncProgressUpdated(
}
/// <summary>Total weight of all progressions being tracked</summary>
private float totalWeight;
/// <summary>Progressions being tracked by this tracker</summary>
private List<ObservedWeightedProgression<ProgressionType>> trackedProgressions;
}
*/
} // namespace Nuclex.Support.Tracking

View File

@ -32,7 +32,7 @@ namespace Nuclex.Support.Tracking {
/// <summary>Performs common initialization for the public constructors</summary>
private SetProgression() {
this.childs = new List<ObservedProgression<ProgressionType>>();
this.childs = new List<ObservedWeightedProgression<ProgressionType>>();
}
/// <summary>Initializes a new set progression</summary>
@ -47,10 +47,10 @@ namespace Nuclex.Support.Tracking {
// progression and wrap it in an ObservedProgression
foreach(ProgressionType progression in childs) {
this.childs.Add(
new ObservedProgression<ProgressionType>(
new ObservedWeightedProgression<ProgressionType>(
new WeightedProgression<ProgressionType>(progression),
new ObservedProgression<ProgressionType>.ReportDelegate(asyncProgressUpdated),
new ObservedProgression<ProgressionType>.ReportDelegate(asyncEnded)
new ObservedWeightedProgression<ProgressionType>.ReportDelegate(asyncProgressUpdated),
new ObservedWeightedProgression<ProgressionType>.ReportDelegate(asyncEnded)
)
);
}
@ -71,10 +71,10 @@ namespace Nuclex.Support.Tracking {
// Construct an ObservedProgression around each of the WeightedProgressions
foreach(WeightedProgression<ProgressionType> progression in childs) {
this.childs.Add(
new ObservedProgression<ProgressionType>(
new ObservedWeightedProgression<ProgressionType>(
progression,
new ObservedProgression<ProgressionType>.ReportDelegate(asyncProgressUpdated),
new ObservedProgression<ProgressionType>.ReportDelegate(asyncEnded)
new ObservedWeightedProgression<ProgressionType>.ReportDelegate(asyncProgressUpdated),
new ObservedWeightedProgression<ProgressionType>.ReportDelegate(asyncEnded)
)
);
@ -110,8 +110,8 @@ namespace Nuclex.Support.Tracking {
// the Childs collection.
if(this.wrapper == null) {
// This doesn't need a lock because it's only a stateless wrapper. If it
// is constructed twice, then so be it.
// This doesn't need a lock because it's a stateless wrapper.
// If it is constructed twice, then so be it, no problem at all.
this.wrapper = new WeightedProgressionWrapperCollection<ProgressionType>(
this.childs
);
@ -127,10 +127,10 @@ namespace Nuclex.Support.Tracking {
/// Called when the progress of one of the observed progressions changes
/// </summary>
private void asyncProgressUpdated() {
float totalProgress = 0.0f;
// Calculate the sum of the progress reported by our child progressions,
// scaled to the weight each progression has assigned to it.
float totalProgress = 0.0f;
for(int index = 0; index < this.childs.Count; ++index) {
totalProgress +=
this.childs[index].Progress * this.childs[index].WeightedProgression.Weight;
@ -142,7 +142,6 @@ namespace Nuclex.Support.Tracking {
// Send out the progress update
OnAsyncProgressUpdated(totalProgress);
}
/// <summary>
@ -162,7 +161,7 @@ namespace Nuclex.Support.Tracking {
}
/// <summary>Progressions being managed in the set</summary>
private List<ObservedProgression<ProgressionType>> childs;
private List<ObservedWeightedProgression<ProgressionType>> childs;
/// <summary>
/// Wrapper collection for exposing the child progressions under the
/// WeightedProgression interface