Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Async/HeuristicLab.Algorithms.DataAnalysis/3.4/FixedDataAnalysisAlgorithm.cs @ 14877

Last change on this file since 14877 was 13349, checked in by jkarder, 9 years ago

#2258: added StartAsync to IExecutable

File size: 4.5 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.Optimization;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28using HeuristicLab.Problems.DataAnalysis;
29
30namespace HeuristicLab.Algorithms.DataAnalysis {
31  [StorableClass]
32  public abstract class FixedDataAnalysisAlgorithm<T> : Algorithm,
33    IDataAnalysisAlgorithm<T>,
34    IStorableContent
35    where T : class, IDataAnalysisProblem {
36    public string Filename { get; set; }
37
38    #region Properties
39    public override Type ProblemType {
40      get { return typeof(T); }
41    }
42    public new T Problem {
43      get { return (T)base.Problem; }
44      set { base.Problem = value; }
45    }
46    [Storable]
47    private ResultCollection results;
48    public override ResultCollection Results {
49      get { return results; }
50    }
51    #endregion
52
53    private DateTime lastUpdateTime;
54
55    [StorableConstructor]
56    protected FixedDataAnalysisAlgorithm(bool deserializing) : base(deserializing) { }
57    protected FixedDataAnalysisAlgorithm(FixedDataAnalysisAlgorithm<T> original, Cloner cloner)
58      : base(original, cloner) {
59      results = cloner.Clone(original.Results);
60    }
61    public FixedDataAnalysisAlgorithm()
62      : base() {
63      results = new ResultCollection();
64    }
65
66    public override void Prepare() {
67      if (Problem != null) base.Prepare();
68      results.Clear();
69      OnPrepared();
70    }
71
72    public override async Task StartAsync(CancellationToken cancellationToken) {
73      await base.StartAsync(cancellationToken);
74      var cancellationTokenSource = new CancellationTokenSource();
75
76      OnStarted();
77      using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, cancellationToken)) {
78        Task task = Task.Factory.StartNew(Run, cts.Token, cts.Token);
79        await task.ContinueWith(t => {
80          try {
81            t.Wait();
82          }
83          catch (AggregateException ex) {
84            try {
85              ex.Flatten().Handle(x => x is OperationCanceledException);
86            }
87            catch (AggregateException remaining) {
88              if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
89              else OnExceptionOccurred(remaining);
90            }
91          }
92          cancellationTokenSource.Dispose();
93          cancellationTokenSource = null;
94          OnStopped();
95        });
96      }
97    }
98    private void Run(object state) {
99      CancellationToken cancellationToken = (CancellationToken)state;
100      lastUpdateTime = DateTime.UtcNow;
101      System.Timers.Timer timer = new System.Timers.Timer(250);
102      timer.AutoReset = true;
103      timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
104      timer.Start();
105      try {
106        Run();
107      }
108      finally {
109        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
110        timer.Stop();
111        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
112      }
113
114      cancellationToken.ThrowIfCancellationRequested();
115    }
116    protected abstract void Run();
117    #region Events
118    protected override void OnProblemChanged() {
119      Problem.Reset += new EventHandler(Problem_Reset);
120      base.OnProblemChanged();
121    }
122    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
123      System.Timers.Timer timer = (System.Timers.Timer)sender;
124      timer.Enabled = false;
125      DateTime now = DateTime.UtcNow;
126      ExecutionTime += now - lastUpdateTime;
127      lastUpdateTime = now;
128      timer.Enabled = true;
129    }
130    #endregion
131
132  }
133}
Note: See TracBrowser for help on using the repository browser.