Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
06/26/17 09:45:36 (7 years ago)
Author:
jkarder
Message:

#2258: refactored async methods

  • synchronously called IExecutables are now executed in the caller's thread
  • removed old synchronization code from unit tests
Location:
branches/Async/HeuristicLab.Optimization/3.3
Files:
6 edited

Legend:

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

    r13354 r15065  
    204204      Prepare();
    205205    }
    206     public void Start() {
    207       StartAsync().Wait();
    208     }
    209     public async Task StartAsync() {
    210       await StartAsync(CancellationToken.None);
    211     }
    212     public virtual async Task StartAsync(CancellationToken cancellationToken) {
     206    public virtual void Start() {
     207      Start(CancellationToken.None);
     208    }
     209    public virtual void Start(CancellationToken cancellationToken) {
    213210      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
    214211        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
     212    }
     213    public virtual async Task StartAsync() { await StartAsync(CancellationToken.None); }
     214    public virtual async Task StartAsync(CancellationToken cancellationToken) {
     215      await Task.Factory.StartNew((ct) => Start((CancellationToken)ct), cancellationToken, cancellationToken);
    215216    }
    216217    public virtual void Pause() {
  • branches/Async/HeuristicLab.Optimization/3.3/Algorithms/BasicAlgorithm.cs

    r13349 r15065  
    6161    }
    6262
    63     public override async Task StartAsync(CancellationToken cancellationToken) {
    64       await base.StartAsync(cancellationToken);
     63    public override void Start() {
     64      base.Start();
    6565      CancellationTokenSource = new CancellationTokenSource();
    6666
    6767      OnStarted();
    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 => {
     68      Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
     69      task.ContinueWith(t => {
     70        try {
     71          t.Wait();
     72        } catch (AggregateException ex) {
    7173          try {
    72             t.Wait();
     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);
    7378          }
    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       }
     79        }
     80        CancellationTokenSource.Dispose();
     81        CancellationTokenSource = null;
     82        OnStopped();
     83      });
    8884    }
    8985
     
    110106      try {
    111107        Run(cancellationToken);
    112       }
    113       finally {
     108      } finally {
    114109        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
    115110        timer.Stop();
  • branches/Async/HeuristicLab.Optimization/3.3/Algorithms/EngineAlgorithm.cs

    r13349 r15065  
    2222using System;
    2323using System.Linq;
    24 using System.Threading;
    25 using System.Threading.Tasks;
    2624using HeuristicLab.Common;
    2725using HeuristicLab.Core;
    2826using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2927using HeuristicLab.PluginInfrastructure;
    30 using ExecutionContext = HeuristicLab.Core.ExecutionContext;
    3128
    3229namespace HeuristicLab.Optimization {
     
    171168      }
    172169    }
    173     public override async Task StartAsync(CancellationToken cancellationToken) {
    174       await base.StartAsync(cancellationToken);
    175       if (engine != null) await engine.StartAsync(cancellationToken);
     170    public override void Start(System.Threading.CancellationToken cancellationToken) {
     171      base.Start(cancellationToken);
     172      if (engine != null) engine.Start(cancellationToken);
    176173    }
    177174    public override void Pause() {
  • branches/Async/HeuristicLab.Optimization/3.3/MetaOptimizers/BatchRun.cs

    r13354 r15065  
    4141  [StorableClass]
    4242  public sealed class BatchRun : NamedItem, IOptimizer, IStorableContent {
    43     private readonly ManualResetEvent signaler = new ManualResetEvent(true);
    44     private CancellationToken cancellationToken;
    45 
    4643    public string Filename { get; set; }
    4744
     
    242239        batchRunAction = BatchRunAction.Prepare;
    243240        // a race-condition may occur when the optimizer has changed the state by itself in the meantime
    244         try { Optimizer.Prepare(clearRuns); }
    245         catch (InvalidOperationException) { }
     241        try { Optimizer.Prepare(clearRuns); } catch (InvalidOperationException) { }
    246242      } else {
    247243        ExecutionState = ExecutionState.Stopped;
     
    249245    }
    250246    public void Start() {
    251       StartAsync().Wait();
    252     }
    253     public async Task StartAsync() {
    254       await StartAsync(CancellationToken.None);
    255     }
     247      Start(CancellationToken.None);
     248    }
     249    public void Start(CancellationToken cancellationToken) {
     250      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
     251        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
     252      if (Optimizer == null) return;
     253      batchRunAction = BatchRunAction.Start;
     254      if (Optimizer.ExecutionState == ExecutionState.Stopped) Optimizer.Prepare();
     255      for (int i = repetitionsCounter; i < repetitions; i++) {
     256        // a race-condition may occur when the optimizer has changed the state by itself in the meantime
     257        try { Optimizer.Start(cancellationToken); } catch (InvalidOperationException) { }
     258        if (ExecutionState == ExecutionState.Paused || ExecutionState == ExecutionState.Stopped) break;
     259        Optimizer.Prepare();
     260      }
     261    }
     262    public async Task StartAsync() { await StartAsync(CancellationToken.None); }
    256263    public async Task StartAsync(CancellationToken cancellationToken) {
    257       this.cancellationToken = cancellationToken;
    258       signaler.Reset();
    259       await Task.Run(async () => {
    260         if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
    261           throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
    262         if (Optimizer == null) return;
    263         batchRunAction = BatchRunAction.Start;
    264         if (Optimizer.ExecutionState == ExecutionState.Stopped) Optimizer.Prepare();
    265         // a race-condition may occur when the optimizer has changed the state by itself in the meantime
    266         try { await Optimizer.StartAsync(cancellationToken); }
    267         catch (InvalidOperationException) { }
    268         signaler.WaitOne();
    269       }, cancellationToken);
     264      await Task.Factory.StartNew((ct) => Start((CancellationToken)ct), cancellationToken, cancellationToken);
    270265    }
    271266    public void Pause() {
     
    276271      if (Optimizer.ExecutionState != ExecutionState.Started) return;
    277272      // a race-condition may occur when the optimizer has changed the state by itself in the meantime
    278       try { Optimizer.Pause(); }
    279       catch (InvalidOperationException) { }
     273      try { Optimizer.Pause(); } catch (InvalidOperationException) { }
    280274    }
    281275    public void Stop() {
     
    289283      }
    290284      // a race-condition may occur when the optimizer has changed the state by itself in the meantime
    291       try { Optimizer.Stop(); }
    292       catch (InvalidOperationException) { }
     285      try { Optimizer.Stop(); } catch (InvalidOperationException) { }
    293286    }
    294287
     
    342335      batchRunAction = BatchRunAction.None;
    343336      ExecutionState = ExecutionState.Paused;
    344       signaler.Set();
    345337      EventHandler handler = Paused;
    346338      if (handler != null) handler(this, EventArgs.Empty);
     
    350342      batchRunAction = BatchRunAction.None;
    351343      ExecutionState = ExecutionState.Stopped;
    352       signaler.Set();
    353344      EventHandler handler = Stopped;
    354345      if (handler != null) handler(this, EventArgs.Empty);
     
    413404      else if (repetitionsCounter >= repetitions) OnStopped();
    414405      else if (batchRunAction == BatchRunAction.Pause) OnPaused();
    415       else if (batchRunAction == BatchRunAction.Start) {
    416         Optimizer.Prepare();
    417         Optimizer.StartAsync(cancellationToken);
    418       } else if (executionState == ExecutionState.Started) {
     406      else if (batchRunAction == BatchRunAction.Start) return;
     407      else if (executionState == ExecutionState.Started) {
    419408        // if the batch run hasn't been started but the inner optimizer was run then pause
    420409        OnPaused();
  • branches/Async/HeuristicLab.Optimization/3.3/MetaOptimizers/Experiment.cs

    r13354 r15065  
    3939  [StorableClass]
    4040  public sealed class Experiment : NamedItem, IOptimizer, IStorableContent {
    41     private readonly ManualResetEvent signaler = new ManualResetEvent(true);
    42     private CancellationToken cancellationToken;
    43 
    4441    public string Filename { get; set; }
    4542
     
    185182      foreach (IOptimizer optimizer in Optimizers.Where(x => x.ExecutionState != ExecutionState.Started)) {
    186183        // a race-condition may occur when the optimizer has changed the state by itself in the meantime
    187         try { optimizer.Prepare(clearRuns); }
    188         catch (InvalidOperationException) { }
     184        try { optimizer.Prepare(clearRuns); } catch (InvalidOperationException) { }
    189185      }
    190186    }
    191187    public void Start() {
    192       StartAsync().Wait();
    193     }
    194     public async Task StartAsync() {
    195       await StartAsync(CancellationToken.None);
    196     }
     188      Start(CancellationToken.None);
     189    }
     190    public void Start(CancellationToken cancellationToken) {
     191      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
     192        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
     193      if (Optimizers.Count == 0) return;
     194
     195      experimentStarted = true;
     196      experimentStopped = false;
     197      IOptimizer optimizer;
     198      while ((optimizer = Optimizers.FirstOrDefault(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused))) != null) {
     199        // a race-condition may occur when the optimizer has changed the state by itself in the meantime
     200        try { optimizer.Start(cancellationToken); } catch (InvalidOperationException) { }
     201        if (ExecutionState == ExecutionState.Paused || ExecutionState == ExecutionState.Stopped) break;
     202      }
     203    }
     204    public async Task StartAsync() { await StartAsync(CancellationToken.None); }
    197205    public async Task StartAsync(CancellationToken cancellationToken) {
    198       this.cancellationToken = cancellationToken;
    199       signaler.Reset();
    200       await Task.Run(async () => {
    201         if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
    202           throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
    203         if (Optimizers.Count == 0) return;
    204 
    205         experimentStarted = true;
    206         experimentStopped = false;
    207         IOptimizer optimizer = Optimizers.FirstOrDefault(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused));
    208         if (optimizer != null) {
    209           // a race-condition may occur when the optimizer has changed the state by itself in the meantime
    210           try { await optimizer.StartAsync(cancellationToken); }
    211           catch (InvalidOperationException) { }
    212         }
    213         signaler.WaitOne();
    214       }, cancellationToken);
     206      await Task.Factory.StartNew((ct) => Start((CancellationToken)ct), cancellationToken, cancellationToken);
    215207    }
    216208    public void Pause() {
     
    223215      foreach (IOptimizer optimizer in Optimizers.Where(x => x.ExecutionState == ExecutionState.Started)) {
    224216        // a race-condition may occur when the optimizer has changed the state by itself in the meantime
    225         try { optimizer.Pause(); }
    226         catch (InvalidOperationException) { }
     217        try { optimizer.Pause(); } catch (InvalidOperationException) { }
    227218      }
    228219    }
     
    237228        foreach (var optimizer in Optimizers.Where(x => (x.ExecutionState == ExecutionState.Started) || (x.ExecutionState == ExecutionState.Paused))) {
    238229          // a race-condition may occur when the optimizer has changed the state by itself in the meantime
    239           try { optimizer.Stop(); }
    240           catch (InvalidOperationException) { }
     230          try { optimizer.Stop(); } catch (InvalidOperationException) { }
    241231        }
    242232      } else {
     
    276266    private void OnPaused() {
    277267      ExecutionState = ExecutionState.Paused;
    278       signaler.Set();
    279268      EventHandler handler = Paused;
    280269      if (handler != null) handler(this, EventArgs.Empty);
     
    283272    private void OnStopped() {
    284273      ExecutionState = ExecutionState.Stopped;
    285       signaler.Set();
    286274      EventHandler handler = Stopped;
    287275      if (handler != null) handler(this, EventArgs.Empty);
     
    374362      try {
    375363        ExecutionTime = Optimizers.Aggregate(TimeSpan.Zero, (t, o) => t + o.ExecutionTime);
    376       }
    377       finally {
     364      } finally {
    378365        Monitor.Exit(locker);
    379366      }
     
    396383          if (Optimizers.All(x => (x.ExecutionState == ExecutionState.Stopped) || (x.ExecutionState == ExecutionState.Prepared))) OnStopped();
    397384        } else {
    398           if (experimentStarted && Optimizers.Any(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused))) {
    399             Optimizers.First(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused)).StartAsync(cancellationToken);
    400           } else if (Optimizers.All(x => x.ExecutionState == ExecutionState.Stopped)) OnStopped();
     385          if (experimentStarted && Optimizers.Any(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused))) return;
     386          else if (Optimizers.All(x => x.ExecutionState == ExecutionState.Stopped)) OnStopped();
    401387          else if (Optimizers.Any(x => (x.ExecutionState == ExecutionState.Prepared) || (x.ExecutionState == ExecutionState.Paused)) && Optimizers.All(o => o.ExecutionState != ExecutionState.Started)) OnPaused();
    402388        }
  • branches/Async/HeuristicLab.Optimization/3.3/MetaOptimizers/TimeLimitRun.cs

    r13354 r15065  
    4141  [StorableClass]
    4242  public sealed class TimeLimitRun : NamedItem, IOptimizer, IStorableContent, INotifyPropertyChanged {
    43     private readonly ManualResetEvent signaler = new ManualResetEvent(true);
    44 
    4543    public string Filename { get; set; }
    4644
     
    241239    }
    242240    public void Start() {
    243       StartAsync().Wait();
    244     }
    245     public async Task StartAsync() {
    246       await StartAsync(CancellationToken.None);
    247     }
     241      Start(CancellationToken.None);
     242    }
     243    public void Start(CancellationToken cancellationToken) {
     244      Algorithm.Start(cancellationToken);
     245    }
     246    public async Task StartAsync() { await StartAsync(CancellationToken.None); }
    248247    public async Task StartAsync(CancellationToken cancellationToken) {
    249       signaler.Reset();
    250       await Task.Run(async () => {
    251         await Algorithm.StartAsync(cancellationToken);
    252         signaler.WaitOne();
    253       }, cancellationToken);
     248      await Task.Factory.StartNew((ct) => Start((CancellationToken)ct), cancellationToken, cancellationToken);
    254249    }
    255250    public void Pause() {
     
    295290    public event EventHandler Paused;
    296291    private void OnPaused() {
    297       if (!pausedForSnapshot && !pausedForTermination) signaler.Set();
    298292      var handler = Paused;
    299293      if (handler != null) handler(this, EventArgs.Empty);
     
    301295    public event EventHandler Stopped;
    302296    private void OnStopped() {
    303       signaler.Set();
    304297      var handler = Stopped;
    305298      if (handler != null) handler(this, EventArgs.Empty);
     
    351344    private void Algorithm_Paused(object sender, EventArgs e) {
    352345      var action = pausedForTermination ? ExecutionState.Stopped : (pausedForSnapshot ? ExecutionState.Started : ExecutionState.Paused);
    353       bool pausedByLimit = pausedForSnapshot || pausedForTermination;
    354       if (pausedByLimit) {
     346      if (pausedForSnapshot || pausedForTermination) {
     347        pausedForSnapshot = pausedForTermination = false;
    355348        MakeSnapshot();
    356349        FindNextSnapshotTimeIndex(ExecutionTime);
    357350      }
    358351      OnPaused();
    359       if (pausedByLimit) pausedForSnapshot = pausedForTermination = false;
    360       if (action == ExecutionState.Started) Algorithm.StartAsync();
     352      if (action == ExecutionState.Started) Algorithm.Start();
    361353      else if (action == ExecutionState.Stopped) Algorithm.Stop();
    362354    }
Note: See TracChangeset for help on using the changeset viewer.