Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PausableBasicAlgorithm/HeuristicLab.Optimization/3.3/Algorithms/BasicAlgorithm.cs @ 15344

Last change on this file since 15344 was 13378, checked in by jkarder, 9 years ago

#2524: made BasicAlgorithm pausable

File size: 4.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
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;
26using HeuristicLab.Core;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28
29namespace HeuristicLab.Optimization {
30  [StorableClass]
31  public abstract class BasicAlgorithm : Algorithm, IStorableContent {
32    public string Filename { get; set; }
33    public virtual bool Pausable { get { return false; } }
34
35    [Storable]
36    private ResultCollection results;
37    public override ResultCollection Results {
38      get { return results; }
39    }
40
41    private CancellationTokenSource cancellationTokenSource;
42    protected CancellationTokenSource CancellationTokenSource {
43      get { return cancellationTokenSource; }
44      private set { cancellationTokenSource = value; }
45    }
46
47    [StorableConstructor]
48    protected BasicAlgorithm(bool deserializing) : base(deserializing) { }
49    protected BasicAlgorithm(BasicAlgorithm original, Cloner cloner)
50      : base(original, cloner) {
51      results = cloner.Clone(original.Results);
52    }
53    protected BasicAlgorithm()
54      : base() {
55      results = new ResultCollection();
56    }
57
58    public override void Prepare() {
59      if (Problem == null) return;
60      base.Prepare();
61      results.Clear();
62      initialized = false;
63      OnPrepared();
64    }
65
66    public override void Start() {
67      base.Start();
68      CancellationTokenSource = new CancellationTokenSource();
69      pausePending = false;
70      OnStarted();
71      Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
72      task.ContinueWith(t => {
73        try {
74          t.Wait();
75        } catch (AggregateException ex) {
76          try {
77            ex.Flatten().Handle(x => x is OperationCanceledException);
78          } catch (AggregateException remaining) {
79            if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
80            else OnExceptionOccurred(remaining);
81          }
82        }
83        CancellationTokenSource.Dispose();
84        CancellationTokenSource = null;
85        if (pausePending) OnPaused();
86        else OnStopped();
87      });
88    }
89
90    private bool pausePending;
91    public override void Pause() {
92      if (!Pausable)
93        throw new NotSupportedException("Pause is not supported by this algorithm.");
94
95      base.Pause();
96      pausePending = Pausable;
97      cancellationTokenSource.Cancel();
98    }
99
100    public override void Stop() {
101      // CancellationToken.ThrowIfCancellationRequested() must be called from within the Run method, otherwise stop does nothing
102      // alternatively check the IsCancellationRequested property of the cancellation token
103      base.Stop();
104      if (ExecutionState == ExecutionState.Paused) OnStopped();
105      else CancellationTokenSource.Cancel();
106    }
107
108
109    private DateTime lastUpdateTime;
110    private void Run(object state) {
111      CancellationToken cancellationToken = (CancellationToken)state;
112      lastUpdateTime = DateTime.UtcNow;
113      System.Timers.Timer timer = new System.Timers.Timer(250);
114      timer.AutoReset = true;
115      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
116      timer.Start();
117      try {
118        if (!initialized)
119          Initialize(cancellationToken);
120        initialized = true;
121        Run(cancellationToken);
122      } finally {
123        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
124        timer.Stop();
125        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
126      }
127    }
128
129    private bool initialized;
130    protected virtual void Initialize(CancellationToken cancellationToken) { }
131    protected abstract void Run(CancellationToken cancellationToken);
132
133    #region Events
134    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
135      System.Timers.Timer timer = (System.Timers.Timer)sender;
136      timer.Enabled = false;
137      DateTime now = DateTime.UtcNow;
138      ExecutionTime += now - lastUpdateTime;
139      lastUpdateTime = now;
140      timer.Enabled = true;
141    }
142    #endregion
143
144  }
145}
Note: See TracBrowser for help on using the repository browser.