Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceOverhaul/HeuristicLab.Optimization/3.3/Algorithms/BasicAlgorithm.cs @ 16529

Last change on this file since 16529 was 14711, checked in by gkronber, 8 years ago

#2520

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