Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
11/24/15 17:46:18 (9 years ago)
Author:
jkarder
Message:

#2524: made BasicAlgorithm pausable

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/PausableBasicAlgorithm/HeuristicLab.Optimization/3.3/Algorithms/BasicAlgorithm.cs

    r11878 r13378  
    2424using System.Threading.Tasks;
    2525using HeuristicLab.Common;
     26using HeuristicLab.Core;
    2627using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2728
     
    3031  public abstract class BasicAlgorithm : Algorithm, IStorableContent {
    3132    public string Filename { get; set; }
     33    public virtual bool Pausable { get { return false; } }
    3234
    3335    [Storable]
     
    5860      base.Prepare();
    5961      results.Clear();
     62      initialized = false;
    6063      OnPrepared();
    6164    }
     
    6467      base.Start();
    6568      CancellationTokenSource = new CancellationTokenSource();
    66 
     69      pausePending = false;
    6770      OnStarted();
    6871      Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
     
    8083        CancellationTokenSource.Dispose();
    8184        CancellationTokenSource = null;
    82         OnStopped();
     85        if (pausePending) OnPaused();
     86        else OnStopped();
    8387      });
    8488    }
    8589
     90    private bool pausePending;
    8691    public override void Pause() {
    87       throw new NotSupportedException("Pause is not supported in basic algorithms.");
     92      if (!Pausable)
     93        throw new NotSupportedException("Pause is not supported by this algorithm.");
     94
     95      base.Pause();
     96      pausePending = Pausable;
     97      cancellationTokenSource.Cancel();
    8898    }
    8999
     
    92102      // alternatively check the IsCancellationRequested property of the cancellation token
    93103      base.Stop();
    94       CancellationTokenSource.Cancel();
     104      if (ExecutionState == ExecutionState.Paused) OnStopped();
     105      else CancellationTokenSource.Cancel();
    95106    }
    96107
     
    105116      timer.Start();
    106117      try {
     118        if (!initialized)
     119          Initialize(cancellationToken);
     120        initialized = true;
    107121        Run(cancellationToken);
    108122      } finally {
     
    113127    }
    114128
     129    private bool initialized;
     130    protected virtual void Initialize(CancellationToken cancellationToken) { }
    115131    protected abstract void Run(CancellationToken cancellationToken);
    116132
Note: See TracChangeset for help on using the changeset viewer.