Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimization/3.3/Algorithms/BasicAlgorithm.cs @ 14517

Last change on this file since 14517 was 14517, checked in by jkarder, 7 years ago

#2524: made BasicAlgorithm pausable

File size: 5.0 KB
RevLine 
[11790]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[11790]4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Threading;
24using System.Threading.Tasks;
25using HeuristicLab.Common;
[14517]26using HeuristicLab.Core;
[11790]27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28
29namespace HeuristicLab.Optimization {
30  [StorableClass]
31  public abstract class BasicAlgorithm : Algorithm, IStorableContent {
[14517]32    private bool initialized;
33    private bool pausePending;
34    private DateTime lastUpdateTime;
35    protected bool pausable;
36
[11790]37    public string Filename { get; set; }
[14517]38    public bool Pausable { get { return pausable; } }
[11790]39
40    [Storable]
41    private ResultCollection results;
42    public override ResultCollection Results {
43      get { return results; }
44    }
45
46    private CancellationTokenSource cancellationTokenSource;
47    protected CancellationTokenSource CancellationTokenSource {
48      get { return cancellationTokenSource; }
49      private set { cancellationTokenSource = value; }
50    }
51
52    [StorableConstructor]
53    protected BasicAlgorithm(bool deserializing) : base(deserializing) { }
54    protected BasicAlgorithm(BasicAlgorithm original, Cloner cloner)
55      : base(original, cloner) {
[14517]56      pausable = original.pausable;
[11790]57      results = cloner.Clone(original.Results);
58    }
59    protected BasicAlgorithm()
60      : base() {
61      results = new ResultCollection();
62    }
63
64    public override void Prepare() {
65      if (Problem == null) return;
66      base.Prepare();
67      results.Clear();
[14517]68      initialized = false;
[11790]69      OnPrepared();
70    }
71
72    public override void Start() {
73      base.Start();
74      CancellationTokenSource = new CancellationTokenSource();
[14517]75      pausePending = false;
[11790]76      OnStarted();
77      Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
78      task.ContinueWith(t => {
79        try {
80          t.Wait();
[11878]81        } catch (AggregateException ex) {
[11790]82          try {
83            ex.Flatten().Handle(x => x is OperationCanceledException);
[11878]84          } catch (AggregateException remaining) {
[11790]85            if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
86            else OnExceptionOccurred(remaining);
87          }
88        }
89        CancellationTokenSource.Dispose();
90        CancellationTokenSource = null;
[14517]91        if (pausePending) OnPaused();
92        else OnStopped();
[11790]93      });
94    }
95
96    public override void Pause() {
[14517]97      if (!Pausable)
98        throw new NotSupportedException("Pause is not supported by this algorithm.");
99
100      base.Pause();
101      pausePending = true;
102      cancellationTokenSource.Cancel();
[11790]103    }
104
105    public override void Stop() {
[11878]106      // CancellationToken.ThrowIfCancellationRequested() must be called from within the Run method, otherwise stop does nothing
107      // alternatively check the IsCancellationRequested property of the cancellation token
[11790]108      base.Stop();
[14517]109      if (ExecutionState == ExecutionState.Paused) OnStopped();
110      else CancellationTokenSource.Cancel();
[11790]111    }
112
113    private void Run(object state) {
114      CancellationToken cancellationToken = (CancellationToken)state;
115      lastUpdateTime = DateTime.UtcNow;
116      System.Timers.Timer timer = new System.Timers.Timer(250);
117      timer.AutoReset = true;
118      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
119      timer.Start();
120      try {
[14517]121        if (!initialized)
122          Initialize(cancellationToken);
123        initialized = true;
[11790]124        Run(cancellationToken);
[11878]125      } finally {
[11790]126        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
127        timer.Stop();
128        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
129      }
130    }
131
[14517]132    protected virtual void Initialize(CancellationToken cancellationToken) { }
[11790]133    protected abstract void Run(CancellationToken cancellationToken);
134
135    #region Events
136    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
137      System.Timers.Timer timer = (System.Timers.Timer)sender;
138      timer.Enabled = false;
139      DateTime now = DateTime.UtcNow;
140      ExecutionTime += now - lastUpdateTime;
141      lastUpdateTime = now;
142      timer.Enabled = true;
143    }
144    #endregion
145
146  }
147}
Note: See TracBrowser for help on using the repository browser.