Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
11/23/15 21:18:26 (9 years ago)
Author:
jkarder
Message:

#2258: added StartAsync to IExecutable

Location:
branches/Async/HeuristicLab.Optimization/3.3
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • branches/Async/HeuristicLab.Optimization/3.3/Algorithms/Algorithm.cs

    r12012 r13349  
    2424using System.Drawing;
    2525using System.Linq;
     26using System.Threading;
     27using System.Threading.Tasks;
    2628using HeuristicLab.Collections;
    2729using HeuristicLab.Common;
     
    202204      Prepare();
    203205    }
    204     public virtual void Start() {
     206    public void Start() {
     207      StartAsync().Wait();
     208    }
     209    public async Task StartAsync() {
     210      await StartAsync(new CancellationToken());
     211    }
     212    public virtual async Task StartAsync(CancellationToken cancellationToken) {
    205213      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
    206214        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
  • branches/Async/HeuristicLab.Optimization/3.3/Algorithms/BasicAlgorithm.cs

    r11878 r13349  
    6161    }
    6262
    63     public override void Start() {
    64       base.Start();
     63    public override async Task StartAsync(CancellationToken cancellationToken) {
     64      await base.StartAsync(cancellationToken);
    6565      CancellationTokenSource = new CancellationTokenSource();
    6666
    6767      OnStarted();
    68       Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
    69       task.ContinueWith(t => {
    70         try {
    71           t.Wait();
    72         } catch (AggregateException ex) {
     68      using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, cancellationToken)) {
     69        Task task = Task.Factory.StartNew(Run, cts.Token, cts.Token);
     70        await task.ContinueWith(t => {
    7371          try {
    74             ex.Flatten().Handle(x => x is OperationCanceledException);
    75           } catch (AggregateException remaining) {
    76             if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
    77             else OnExceptionOccurred(remaining);
     72            t.Wait();
    7873          }
    79         }
    80         CancellationTokenSource.Dispose();
    81         CancellationTokenSource = null;
    82         OnStopped();
    83       });
     74          catch (AggregateException ex) {
     75            try {
     76              ex.Flatten().Handle(x => x is OperationCanceledException);
     77            }
     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          OnStopped();
     86        });
     87      }
    8488    }
    8589
     
    106110      try {
    107111        Run(cancellationToken);
    108       } finally {
     112      }
     113      finally {
    109114        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
    110115        timer.Stop();
  • branches/Async/HeuristicLab.Optimization/3.3/Algorithms/EngineAlgorithm.cs

    r12012 r13349  
    2222using System;
    2323using System.Linq;
     24using System.Threading;
     25using System.Threading.Tasks;
    2426using HeuristicLab.Common;
    2527using HeuristicLab.Core;
    2628using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2729using HeuristicLab.PluginInfrastructure;
     30using ExecutionContext = HeuristicLab.Core.ExecutionContext;
    2831
    2932namespace HeuristicLab.Optimization {
     
    168171      }
    169172    }
    170     public override void Start() {
    171       base.Start();
    172       if (engine != null) engine.Start();
     173    public override async Task StartAsync(CancellationToken cancellationToken) {
     174      await base.StartAsync(cancellationToken);
     175      if (engine != null) await engine.StartAsync(cancellationToken);
    173176    }
    174177    public override void Pause() {
  • branches/Async/HeuristicLab.Optimization/3.3/MetaOptimizers/BatchRun.cs

    r12504 r13349  
    2323using System.Collections.Generic;
    2424using System.Drawing;
     25using System.Threading;
     26using System.Threading.Tasks;
    2527using HeuristicLab.Collections;
    2628using HeuristicLab.Common;
     
    3941  [StorableClass]
    4042  public sealed class BatchRun : NamedItem, IOptimizer, IStorableContent {
     43    private readonly ManualResetEvent signaler = new ManualResetEvent(true);
     44
    4145    public string Filename { get; set; }
    4246
     
    244248    }
    245249    public void Start() {
    246       if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
    247         throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
    248       if (Optimizer == null) return;
    249       batchRunAction = BatchRunAction.Start;
    250       if (Optimizer.ExecutionState == ExecutionState.Stopped) Optimizer.Prepare();
    251       // a race-condition may occur when the optimizer has changed the state by itself in the meantime
    252       try { Optimizer.Start(); }
    253       catch (InvalidOperationException) { }
     250      StartAsync().Wait();
     251    }
     252    public async Task StartAsync() {
     253      await StartAsync(new CancellationToken());
     254    }
     255    public async Task StartAsync(CancellationToken cancellationToken) {
     256      signaler.Reset();
     257      await Task.Run(async () => {
     258        if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
     259          throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
     260        if (Optimizer == null) return;
     261        batchRunAction = BatchRunAction.Start;
     262        if (Optimizer.ExecutionState == ExecutionState.Stopped) Optimizer.Prepare();
     263        // a race-condition may occur when the optimizer has changed the state by itself in the meantime
     264        try { await Optimizer.StartAsync(cancellationToken); }
     265        catch (InvalidOperationException) { }
     266        signaler.WaitOne();
     267      }, cancellationToken);
    254268    }
    255269    public void Pause() {
     
    326340      batchRunAction = BatchRunAction.None;
    327341      ExecutionState = ExecutionState.Paused;
     342      signaler.Set();
    328343      EventHandler handler = Paused;
    329344      if (handler != null) handler(this, EventArgs.Empty);
     
    333348      batchRunAction = BatchRunAction.None;
    334349      ExecutionState = ExecutionState.Stopped;
     350      signaler.Set();
    335351      EventHandler handler = Stopped;
    336352      if (handler != null) handler(this, EventArgs.Empty);
     
    397413      else if (batchRunAction == BatchRunAction.Start) {
    398414        Optimizer.Prepare();
    399         Optimizer.Start();
     415        Optimizer.StartAsync();
    400416      } else if (executionState == ExecutionState.Started) {
    401417        // if the batch run hasn't been started but the inner optimizer was run then pause
  • branches/Async/HeuristicLab.Optimization/3.3/MetaOptimizers/Experiment.cs

    r13000 r13349  
    2525using System.Linq;
    2626using System.Threading;
     27using System.Threading.Tasks;
    2728using HeuristicLab.Collections;
    2829using HeuristicLab.Common;
     
    3839  [StorableClass]
    3940  public sealed class Experiment : NamedItem, IOptimizer, IStorableContent {
     41    private readonly ManualResetEvent signaler = new ManualResetEvent(true);
     42
    4043    public string Filename { get; set; }
    4144
     
    186189    }
    187190    public void Start() {
    188       if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
    189         throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
    190       if (Optimizers.Count == 0) return;
    191 
    192       experimentStarted = true;
    193       experimentStopped = false;
    194       IOptimizer optimizer = Optimizers.FirstOrDefault(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused));
    195       if (optimizer != null) {
    196         // a race-condition may occur when the optimizer has changed the state by itself in the meantime
    197         try { optimizer.Start(); }
    198         catch (InvalidOperationException) { }
    199       }
     191      StartAsync().Wait();
     192    }
     193    public async Task StartAsync() {
     194      await StartAsync(new CancellationToken());
     195    }
     196    public async Task StartAsync(CancellationToken cancellationToken) {
     197      signaler.Reset();
     198      await Task.Run(async () => {
     199        if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
     200          throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
     201        if (Optimizers.Count == 0) return;
     202
     203        experimentStarted = true;
     204        experimentStopped = false;
     205        IOptimizer optimizer = Optimizers.FirstOrDefault(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused));
     206        if (optimizer != null) {
     207          // a race-condition may occur when the optimizer has changed the state by itself in the meantime
     208          try { await optimizer.StartAsync(cancellationToken); }
     209          catch (InvalidOperationException) { }
     210        }
     211        signaler.WaitOne();
     212      }, cancellationToken);
    200213    }
    201214    public void Pause() {
     
    261274    private void OnPaused() {
    262275      ExecutionState = ExecutionState.Paused;
     276      signaler.Set();
    263277      EventHandler handler = Paused;
    264278      if (handler != null) handler(this, EventArgs.Empty);
     
    267281    private void OnStopped() {
    268282      ExecutionState = ExecutionState.Stopped;
     283      signaler.Set();
    269284      EventHandler handler = Stopped;
    270285      if (handler != null) handler(this, EventArgs.Empty);
     
    380395        } else {
    381396          if (experimentStarted && Optimizers.Any(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused))) {
    382             Optimizers.First(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused)).Start();
     397            Optimizers.First(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused)).StartAsync();
    383398          } else if (Optimizers.All(x => x.ExecutionState == ExecutionState.Stopped)) OnStopped();
    384399          else if (Optimizers.Any(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused)) && Optimizers.All(o => o.ExecutionState != ExecutionState.Started)) OnPaused();
  • branches/Async/HeuristicLab.Optimization/3.3/MetaOptimizers/TimeLimitRun.cs

    r13321 r13349  
    2525using System.Drawing;
    2626using System.Linq;
     27using System.Threading;
    2728using System.Threading.Tasks;
    2829using HeuristicLab.Collections;
     
    4041  [StorableClass]
    4142  public sealed class TimeLimitRun : NamedItem, IOptimizer, IStorableContent, INotifyPropertyChanged {
     43    private readonly ManualResetEvent signaler = new ManualResetEvent(true);
     44
    4245    public string Filename { get; set; }
    4346
     
    238241    }
    239242    public void Start() {
    240       Algorithm.Start();
     243      StartAsync().Wait();
     244    }
     245    public async Task StartAsync() {
     246      await StartAsync(new CancellationToken());
     247    }
     248    public async Task StartAsync(CancellationToken cancellationToken) {
     249      signaler.Reset();
     250      await Task.Run(async () => {
     251        await Algorithm.StartAsync(cancellationToken);
     252        signaler.WaitOne();
     253      }, cancellationToken);
    241254    }
    242255    public void Pause() {
     
    282295    public event EventHandler Paused;
    283296    private void OnPaused() {
     297      if (!pausedForSnapshot && !pausedForTermination) signaler.Set();
    284298      var handler = Paused;
    285299      if (handler != null) handler(this, EventArgs.Empty);
     
    287301    public event EventHandler Stopped;
    288302    private void OnStopped() {
     303      signaler.Set();
    289304      var handler = Stopped;
    290305      if (handler != null) handler(this, EventArgs.Empty);
     
    336351    private void Algorithm_Paused(object sender, EventArgs e) {
    337352      var action = pausedForTermination ? ExecutionState.Stopped : (pausedForSnapshot ? ExecutionState.Started : ExecutionState.Paused);
    338       if (pausedForSnapshot || pausedForTermination) {
    339         pausedForSnapshot = pausedForTermination = false;
     353      bool pausedByLimit = pausedForSnapshot || pausedForTermination;
     354      if (pausedByLimit) {
    340355        MakeSnapshot();
    341356        FindNextSnapshotTimeIndex(ExecutionTime);
    342357      }
    343358      OnPaused();
    344       if (action == ExecutionState.Started) Algorithm.Start();
     359      if (pausedByLimit) pausedForSnapshot = pausedForTermination = false;
     360      if (action == ExecutionState.Started) Algorithm.StartAsync();
    345361      else if (action == ExecutionState.Stopped) Algorithm.Stop();
    346362    }
Note: See TracChangeset for help on using the changeset viewer.