Free cookie consent management tool by TermsFeed Policy Generator

Changeset 13349


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

#2258: added StartAsync to IExecutable

Location:
branches/Async
Files:
21 edited

Legend:

Unmodified
Added
Removed
  • branches/Async/HeuristicLab.Algorithms.Benchmarks/3.3/BenchmarkAlgorithm.cs

    r12504 r13349  
    302302    }
    303303    public void Start() {
     304      StartAsync().Wait();
     305    }
     306    public async Task StartAsync() {
     307      await StartAsync(new CancellationToken());
     308    }
     309    public async Task StartAsync(CancellationToken cancellationToken) {
    304310      cancellationTokenSource = new CancellationTokenSource();
    305311      OnStarted();
    306       Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
    307       task.ContinueWith(t => {
    308         try {
    309           t.Wait();
    310         }
    311         catch (AggregateException ex) {
     312      using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, cancellationToken)) {
     313        Task task = Task.Factory.StartNew(Run, cts.Token, cts.Token);
     314        await task.ContinueWith(t => {
    312315          try {
    313             ex.Flatten().Handle(x => x is OperationCanceledException);
     316            t.Wait();
    314317          }
    315           catch (AggregateException remaining) {
    316             if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
    317             else OnExceptionOccurred(remaining);
     318          catch (AggregateException ex) {
     319            try {
     320              ex.Flatten().Handle(x => x is OperationCanceledException);
     321            }
     322            catch (AggregateException remaining) {
     323              if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
     324              else OnExceptionOccurred(remaining);
     325            }
    318326          }
    319         }
    320 
    321         cancellationTokenSource.Dispose();
    322         cancellationTokenSource = null;
    323         OnStopped();
    324       });
    325     }
    326 
     327
     328          cancellationTokenSource.Dispose();
     329          cancellationTokenSource = null;
     330          OnStopped();
     331        });
     332      }
     333    }
    327334    private void Run(object state) {
    328335      CancellationToken cancellationToken = (CancellationToken)state;
  • branches/Async/HeuristicLab.Algorithms.DataAnalysis.Views/3.4/CrossValidationView.cs

    r12012 r13349  
    216216
    217217    private void startButton_Click(object sender, EventArgs e) {
    218       Content.Start();
     218      Content.StartAsync();
    219219    }
    220220    private void pauseButton_Click(object sender, EventArgs e) {
  • branches/Async/HeuristicLab.Algorithms.DataAnalysis/3.4/CrossValidation.cs

    r13238 r13349  
    2525using System.Linq;
    2626using System.Threading;
     27using System.Threading.Tasks;
    2728using HeuristicLab.Collections;
    2829using HeuristicLab.Common;
     
    3940  [StorableClass]
    4041  public sealed class CrossValidation : ParameterizedNamedItem, IAlgorithm, IStorableContent {
     42    private readonly ManualResetEvent signaler = new ManualResetEvent(true);
     43
    4144    public CrossValidation()
    4245      : base() {
     
    265268      Prepare();
    266269    }
    267 
    268270    public void Start() {
    269       if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
    270         throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
    271 
    272       if (Algorithm != null) {
    273         //create cloned algorithms
    274         if (clonedAlgorithms.Count == 0) {
    275           int testSamplesCount = (SamplesEnd.Value - SamplesStart.Value) / Folds.Value;
    276 
    277           for (int i = 0; i < Folds.Value; i++) {
    278             IAlgorithm clonedAlgorithm = (IAlgorithm)algorithm.Clone();
    279             clonedAlgorithm.Name = algorithm.Name + " Fold " + i;
    280             IDataAnalysisProblem problem = clonedAlgorithm.Problem as IDataAnalysisProblem;
    281             ISymbolicDataAnalysisProblem symbolicProblem = problem as ISymbolicDataAnalysisProblem;
    282 
    283             int testStart = (i * testSamplesCount) + SamplesStart.Value;
    284             int testEnd = (i + 1) == Folds.Value ? SamplesEnd.Value : (i + 1) * testSamplesCount + SamplesStart.Value;
    285 
    286             problem.ProblemData.TrainingPartition.Start = SamplesStart.Value;
    287             problem.ProblemData.TrainingPartition.End = SamplesEnd.Value;
    288             problem.ProblemData.TestPartition.Start = testStart;
    289             problem.ProblemData.TestPartition.End = testEnd;
    290             DataAnalysisProblemData problemData = problem.ProblemData as DataAnalysisProblemData;
    291             if (problemData != null) {
    292               problemData.TrainingPartitionParameter.Hidden = false;
    293               problemData.TestPartitionParameter.Hidden = false;
     271      StartAsync().Wait();
     272    }
     273    public async Task StartAsync() {
     274      await StartAsync(new CancellationToken());
     275    }
     276    public async Task StartAsync(CancellationToken cancellationToken) {
     277      signaler.Reset();
     278      await Task.Run(() => {
     279        if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
     280          throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
     281
     282        if (Algorithm != null) {
     283          //create cloned algorithms
     284          if (clonedAlgorithms.Count == 0) {
     285            int testSamplesCount = (SamplesEnd.Value - SamplesStart.Value) / Folds.Value;
     286
     287            for (int i = 0; i < Folds.Value; i++) {
     288              IAlgorithm clonedAlgorithm = (IAlgorithm)algorithm.Clone();
     289              clonedAlgorithm.Name = algorithm.Name + " Fold " + i;
     290              IDataAnalysisProblem problem = clonedAlgorithm.Problem as IDataAnalysisProblem;
     291              ISymbolicDataAnalysisProblem symbolicProblem = problem as ISymbolicDataAnalysisProblem;
     292
     293              int testStart = (i * testSamplesCount) + SamplesStart.Value;
     294              int testEnd = (i + 1) == Folds.Value ? SamplesEnd.Value : (i + 1) * testSamplesCount + SamplesStart.Value;
     295
     296              problem.ProblemData.TrainingPartition.Start = SamplesStart.Value;
     297              problem.ProblemData.TrainingPartition.End = SamplesEnd.Value;
     298              problem.ProblemData.TestPartition.Start = testStart;
     299              problem.ProblemData.TestPartition.End = testEnd;
     300              DataAnalysisProblemData problemData = problem.ProblemData as DataAnalysisProblemData;
     301              if (problemData != null) {
     302                problemData.TrainingPartitionParameter.Hidden = false;
     303                problemData.TestPartitionParameter.Hidden = false;
     304              }
     305
     306              if (symbolicProblem != null) {
     307                symbolicProblem.FitnessCalculationPartition.Start = SamplesStart.Value;
     308                symbolicProblem.FitnessCalculationPartition.End = SamplesEnd.Value;
     309              }
     310              clonedAlgorithm.Prepare();
     311              clonedAlgorithms.Add(clonedAlgorithm);
    294312            }
    295 
    296             if (symbolicProblem != null) {
    297               symbolicProblem.FitnessCalculationPartition.Start = SamplesStart.Value;
    298               symbolicProblem.FitnessCalculationPartition.End = SamplesEnd.Value;
    299             }
    300             clonedAlgorithm.Prepare();
    301             clonedAlgorithms.Add(clonedAlgorithm);
    302313          }
    303         }
    304 
    305         //start prepared or paused cloned algorithms
    306         int startedAlgorithms = 0;
    307         foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
    308           if (startedAlgorithms < NumberOfWorkers.Value) {
    309             if (clonedAlgorithm.ExecutionState == ExecutionState.Prepared ||
    310                 clonedAlgorithm.ExecutionState == ExecutionState.Paused) {
    311 
    312               // start and wait until the alg is started
    313               using (var signal = new ManualResetEvent(false)) {
    314                 EventHandler signalSetter = (sender, args) => { signal.Set(); };
    315                 clonedAlgorithm.Started += signalSetter;
    316                 clonedAlgorithm.Start();
    317                 signal.WaitOne();
    318                 clonedAlgorithm.Started -= signalSetter;
    319 
    320                 startedAlgorithms++;
     314
     315          //start prepared or paused cloned algorithms
     316          int startedAlgorithms = 0;
     317          foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
     318            if (startedAlgorithms < NumberOfWorkers.Value) {
     319              if (clonedAlgorithm.ExecutionState == ExecutionState.Prepared ||
     320                  clonedAlgorithm.ExecutionState == ExecutionState.Paused) {
     321
     322                // start and wait until the alg is started
     323                using (var signal = new ManualResetEvent(false)) {
     324                  EventHandler signalSetter = (sender, args) => { signal.Set(); };
     325                  clonedAlgorithm.Started += signalSetter;
     326                  clonedAlgorithm.StartAsync(cancellationToken);
     327                  signal.WaitOne();
     328                  clonedAlgorithm.Started -= signalSetter;
     329
     330                  startedAlgorithms++;
     331                }
    321332              }
    322333            }
    323334          }
    324         }
    325         OnStarted();
    326       }
     335          OnStarted();
     336        }
     337      }, cancellationToken);
    327338    }
    328339
     
    671682          IAlgorithm preparedAlgorithm = clonedAlgorithms.FirstOrDefault(alg => alg.ExecutionState == ExecutionState.Prepared ||
    672683                                                                                alg.ExecutionState == ExecutionState.Paused);
    673           if (preparedAlgorithm != null) preparedAlgorithm.Start();
     684          if (preparedAlgorithm != null) preparedAlgorithm.StartAsync();
    674685        }
    675686        if (ExecutionState != ExecutionState.Stopped) {
     
    714725      pausePending = false;
    715726      ExecutionState = ExecutionState.Paused;
     727      signaler.Set();
    716728      EventHandler handler = Paused;
    717729      if (handler != null) handler(this, EventArgs.Empty);
     
    726738      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
    727739      ExecutionState = ExecutionState.Stopped;
     740      signaler.Set();
    728741      EventHandler handler = Stopped;
    729742      if (handler != null) handler(this, EventArgs.Empty);
  • branches/Async/HeuristicLab.Algorithms.DataAnalysis/3.4/FixedDataAnalysisAlgorithm.cs

    r12012 r13349  
    7070    }
    7171
    72     public override void Start() {
    73       base.Start();
     72    public override async Task StartAsync(CancellationToken cancellationToken) {
     73      await base.StartAsync(cancellationToken);
    7474      var cancellationTokenSource = new CancellationTokenSource();
    7575
    7676      OnStarted();
    77       Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
    78       task.ContinueWith(t => {
    79         try {
    80           t.Wait();
    81         }
    82         catch (AggregateException ex) {
     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 => {
    8380          try {
    84             ex.Flatten().Handle(x => x is OperationCanceledException);
     81            t.Wait();
    8582          }
    86           catch (AggregateException remaining) {
    87             if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
    88             else OnExceptionOccurred(remaining);
     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            }
    8991          }
    90         }
    91         cancellationTokenSource.Dispose();
    92         cancellationTokenSource = null;
    93         OnStopped();
    94       });
     92          cancellationTokenSource.Dispose();
     93          cancellationTokenSource = null;
     94          OnStopped();
     95        });
     96      }
    9597    }
    9698    private void Run(object state) {
  • branches/Async/HeuristicLab.Clients.Hive/3.3/Tasks/EngineTask.cs

    r12012 r13349  
    8181    public override void Start() {
    8282      Item.Prepare(initialOperation);
    83       Item.Start();
     83      Item.StartAsync();
    8484    }
    8585
  • branches/Async/HeuristicLab.Clients.Hive/3.3/Tasks/OptimizerTask.cs

    r12012 r13349  
    101101        OnTaskStopped();
    102102      } else {
    103         Item.Start();
     103        Item.StartAsync();
    104104      }
    105105    }
  • branches/Async/HeuristicLab.Clients.OKB.Views/3.3/RunCreation/Views/OKBAlgorithmView.cs

    r12012 r13349  
    325325    }
    326326    private void startButton_Click(object sender, EventArgs e) {
    327       Content.Start();
     327      Content.StartAsync();
    328328    }
    329329    private void pauseButton_Click(object sender, EventArgs e) {
  • branches/Async/HeuristicLab.Clients.OKB/3.3/RunCreation/EmptyAlgorithm.cs

    r12012 r13349  
    2121
    2222using System;
     23using System.Threading;
     24using System.Threading.Tasks;
    2325using HeuristicLab.Common;
    2426using HeuristicLab.Core;
     
    8082      throw new InvalidOperationException(string.IsNullOrEmpty(exceptionMessage) ? "Cannot prepare an EmptyAlgorithm." : exceptionMessage);
    8183    }
    82     public override void Start() {
     84    public override async Task StartAsync(CancellationToken cancellationToken) {
    8385      throw new InvalidOperationException(string.IsNullOrEmpty(exceptionMessage) ? "Cannot start an EmptyAlgorithm." : exceptionMessage);
    8486    }
  • branches/Async/HeuristicLab.Clients.OKB/3.3/RunCreation/OKBAlgorithm.cs

    r12504 r13349  
    2525using System.IO;
    2626using System.Linq;
     27using System.Threading;
     28using System.Threading.Tasks;
    2729using HeuristicLab.Clients.Access;
    2830using HeuristicLab.Collections;
     
    250252    }
    251253    public void Start() {
     254      StartAsync().Wait();
     255    }
     256    public async Task StartAsync() {
     257      await StartAsync(new CancellationToken());
     258    }
     259    public async Task StartAsync(CancellationToken cancellationToken) {
    252260      CheckUserPermissions();
    253261      if (!ClientInformation.Instance.ClientExists && storeRunsAutomatically) {
    254262        throw new MissingClientRegistrationException();
    255263      }
    256       Algorithm.Start();
     264      await Algorithm.StartAsync(cancellationToken);
    257265    }
    258266    public void Pause() {
  • branches/Async/HeuristicLab.Core/3.3/Engine.cs

    r12012 r13349  
    8282    }
    8383
    84     public override void Start() {
    85       base.Start();
     84    public override async Task StartAsync(CancellationToken cancellationToken) {
     85      await base.StartAsync(cancellationToken);
    8686      cancellationTokenSource = new CancellationTokenSource();
    8787      stopPending = false;
    88       Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
    89       task.ContinueWith(t => {
    90         try {
    91           t.Wait();
    92         }
    93         catch (AggregateException ex) {
     88      using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, cancellationToken)) {
     89        Task task = Task.Factory.StartNew(Run, cts.Token, cts.Token);
     90        await task.ContinueWith(t => {
    9491          try {
    95             ex.Flatten().Handle(x => x is OperationCanceledException);
     92            t.Wait();
    9693          }
    97           catch (AggregateException remaining) {
    98             if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
    99             else OnExceptionOccurred(remaining);
     94          catch (AggregateException ex) {
     95            try {
     96              ex.Flatten().Handle(x => x is OperationCanceledException);
     97            }
     98            catch (AggregateException remaining) {
     99              if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
     100              else OnExceptionOccurred(remaining);
     101            }
    100102          }
    101         }
    102         cancellationTokenSource.Dispose();
    103         cancellationTokenSource = null;
    104         if (stopPending) executionStack.Clear();
    105         if (executionStack.Count == 0) OnStopped();
    106         else OnPaused();
    107       });
     103          cancellationTokenSource.Dispose();
     104          cancellationTokenSource = null;
     105          if (stopPending) executionStack.Clear();
     106          if (executionStack.Count == 0) OnStopped();
     107          else OnPaused();
     108        });
     109      }
    108110    }
    109111    protected override void OnStarted() {
  • branches/Async/HeuristicLab.Core/3.3/Executable.cs

    r12012 r13349  
    2222using System;
    2323using System.Drawing;
     24using System.Threading;
     25using System.Threading.Tasks;
    2426using HeuristicLab.Common;
    2527using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     
    8284      ExecutionTime = TimeSpan.Zero;
    8385    }
    84     public virtual void Start() {
     86    public void Start() {
     87      StartAsync().Wait();
     88    }
     89    public async Task StartAsync() {
     90      await StartAsync(new CancellationToken());
     91    }
     92    public virtual async Task StartAsync(CancellationToken cancellationToken) {
    8593      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
    8694        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
  • branches/Async/HeuristicLab.Core/3.3/Interfaces/IExecutable.cs

    r12012 r13349  
    2121
    2222using System;
     23using System.Threading;
     24using System.Threading.Tasks;
    2325using HeuristicLab.Common;
    2426
     
    3032    void Prepare();
    3133    void Start();
     34    Task StartAsync();
     35    Task StartAsync(CancellationToken cancellationToken);
    3236    void Pause();
    3337    void Stop();
  • branches/Async/HeuristicLab.DebugEngine/3.3/DebugEngine.cs

    r12012 r13349  
    174174    }
    175175
    176     public override void Start() {
    177       base.Start();
     176    public override async Task StartAsync(CancellationToken cancellationToken) {
     177      await base.StartAsync(cancellationToken);
    178178      cancellationTokenSource = new CancellationTokenSource();
    179179      stopPending = false;
    180       Task task = Task.Factory.StartNew(Run, cancellationTokenSource.Token, cancellationTokenSource.Token);
    181       task.ContinueWith(t => {
    182         try {
    183           t.Wait();
    184         }
    185         catch (AggregateException ex) {
     180      using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, cancellationToken)) {
     181        Task task = Task.Factory.StartNew(Run, cts.Token, cts.Token);
     182        await task.ContinueWith(t => {
    186183          try {
    187             ex.Flatten().Handle(x => x is OperationCanceledException);
     184            t.Wait();
    188185          }
    189           catch (AggregateException remaining) {
    190             if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
    191             else OnExceptionOccurred(remaining);
     186          catch (AggregateException ex) {
     187            try {
     188              ex.Flatten().Handle(x => x is OperationCanceledException);
     189            }
     190            catch (AggregateException remaining) {
     191              if (remaining.InnerExceptions.Count == 1) OnExceptionOccurred(remaining.InnerExceptions[0]);
     192              else OnExceptionOccurred(remaining);
     193            }
    192194          }
    193         }
    194         cancellationTokenSource.Dispose();
    195         cancellationTokenSource = null;
    196 
    197         if (stopPending) ExecutionStack.Clear();
    198         if (stopPending || !CanContinue) OnStopped();
    199         else OnPaused();
    200       });
     195          cancellationTokenSource.Dispose();
     196          cancellationTokenSource = null;
     197
     198          if (stopPending) ExecutionStack.Clear();
     199          if (stopPending || !CanContinue) OnStopped();
     200          else OnPaused();
     201        });
     202      }
    201203    }
    202204
  • branches/Async/HeuristicLab.Optimization.Views/3.3/IOptimizerView.cs

    r12012 r13349  
    137137    #region Control events
    138138    protected virtual void startButton_Click(object sender, EventArgs e) {
    139       Content.Start();
     139      Content.StartAsync();
    140140    }
    141141    protected virtual void pauseButton_Click(object sender, EventArgs e) {
  • 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    }
  • branches/Async/HeuristicLab.Problems.QuadraticAssignment.Algorithms/3.3/RobustTabooSearch.cs

    r13173 r13349  
    2222using System;
    2323using System.Linq;
     24using System.Threading;
     25using System.Threading.Tasks;
    2426using HeuristicLab.Analysis;
    2527using HeuristicLab.Common;
     
    338340    }
    339341
    340     public override void Start() {
     342    public override async Task StartAsync(CancellationToken cancellationToken) {
    341343      if (ExecutionState == ExecutionState.Prepared) {
    342344        int dim = Problem.Weights.Rows;
     
    350352        GlobalScope.Variables.Add(new Variable("MoveQualityMatrix", new DoubleMatrix(dim, dim)));
    351353      }
    352       base.Start();
     354      await base.StartAsync(cancellationToken);
    353355    }
    354356
Note: See TracChangeset for help on using the changeset viewer.