Free cookie consent management tool by TermsFeed Policy Generator

Changeset 15065 for branches


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
Files:
1 deleted
23 edited

Legend:

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

    r13354 r15065  
    302302    }
    303303    public void Start() {
    304       StartAsync().Wait();
    305     }
    306     public async Task StartAsync() {
    307       await StartAsync(CancellationToken.None);
    308     }
     304      Start(CancellationToken.None);
     305    }
     306    public void Start(CancellationToken cancellationToken) {
     307      cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
     308      OnStarted();
     309
     310      try {
     311        Run(cancellationTokenSource.Token);
     312      } catch (OperationCanceledException) {
     313      } catch (AggregateException ae) {
     314        if (ae.InnerExceptions.Count == 1) OnExceptionOccurred(ae.InnerExceptions[0]);
     315        else OnExceptionOccurred(ae);
     316      } catch (Exception e) {
     317        OnExceptionOccurred(e);
     318      }
     319
     320      cancellationTokenSource.Dispose();
     321      cancellationTokenSource = null;
     322      OnStopped();
     323    }
     324    public async Task StartAsync() { await StartAsync(CancellationToken.None); }
    309325    public async Task StartAsync(CancellationToken cancellationToken) {
    310       cancellationTokenSource = new CancellationTokenSource();
    311       OnStarted();
    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 => {
    315           try {
    316             t.Wait();
    317           }
    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             }
    326           }
    327 
    328           cancellationTokenSource.Dispose();
    329           cancellationTokenSource = null;
    330           OnStopped();
    331         });
    332       }
    333     }
     326      await Task.Factory.StartNew((ct) => Start((CancellationToken)ct), cancellationToken, cancellationToken);
     327    }
     328
    334329    private void Run(object state) {
    335330      CancellationToken cancellationToken = (CancellationToken)state;
     
    353348        Benchmark.TimeLimit = timelimit;
    354349        Benchmark.Run(cancellationToken, results);
    355       }
    356       catch (OperationCanceledException) {
    357       }
    358       finally {
     350      } catch (OperationCanceledException) {
     351      } finally {
    359352        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
    360353        timer.Stop();
  • branches/Async/HeuristicLab.Algorithms.DataAnalysis/3.4/CrossValidation.cs

    r13354 r15065  
    4040  [StorableClass]
    4141  public sealed class CrossValidation : ParameterizedNamedItem, IAlgorithm, IStorableContent {
    42     private readonly ManualResetEvent signaler = new ManualResetEvent(true);
    43     private CancellationToken cancellationToken;
     42    private SemaphoreSlim ticket;
     43    private ManualResetEventSlim signal;
    4444
    4545    public CrossValidation()
     
    269269      Prepare();
    270270    }
     271
    271272    public void Start() {
    272       StartAsync().Wait();
    273     }
    274     public async Task StartAsync() {
    275       await StartAsync(CancellationToken.None);
    276     }
     273      Start(CancellationToken.None);
     274    }
     275    public void Start(CancellationToken cancellationToken) {
     276      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
     277        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
     278
     279      if (Algorithm == null) return;
     280      //create cloned algorithms
     281      if (clonedAlgorithms.Count == 0) {
     282        int testSamplesCount = (SamplesEnd.Value - SamplesStart.Value) / Folds.Value;
     283
     284        for (int i = 0; i < Folds.Value; i++) {
     285          IAlgorithm clonedAlgorithm = (IAlgorithm)algorithm.Clone();
     286          clonedAlgorithm.Name = algorithm.Name + " Fold " + i;
     287          IDataAnalysisProblem problem = clonedAlgorithm.Problem as IDataAnalysisProblem;
     288          ISymbolicDataAnalysisProblem symbolicProblem = problem as ISymbolicDataAnalysisProblem;
     289
     290          int testStart = (i * testSamplesCount) + SamplesStart.Value;
     291          int testEnd = (i + 1) == Folds.Value ? SamplesEnd.Value : (i + 1) * testSamplesCount + SamplesStart.Value;
     292
     293          problem.ProblemData.TrainingPartition.Start = SamplesStart.Value;
     294          problem.ProblemData.TrainingPartition.End = SamplesEnd.Value;
     295          problem.ProblemData.TestPartition.Start = testStart;
     296          problem.ProblemData.TestPartition.End = testEnd;
     297          DataAnalysisProblemData problemData = problem.ProblemData as DataAnalysisProblemData;
     298          if (problemData != null) {
     299            problemData.TrainingPartitionParameter.Hidden = false;
     300            problemData.TestPartitionParameter.Hidden = false;
     301          }
     302
     303          if (symbolicProblem != null) {
     304            symbolicProblem.FitnessCalculationPartition.Start = SamplesStart.Value;
     305            symbolicProblem.FitnessCalculationPartition.End = SamplesEnd.Value;
     306          }
     307          clonedAlgorithm.Prepare();
     308          clonedAlgorithms.Add(clonedAlgorithm);
     309        }
     310      }
     311
     312      OnStarted();
     313      ticket = new SemaphoreSlim(NumberOfWorkers.Value);
     314      signal = new ManualResetEventSlim(false);
     315
     316      //start prepared or paused cloned algorithms
     317      foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
     318        if (pausePending || stopPending) break;
     319        if (clonedAlgorithm.ExecutionState == ExecutionState.Prepared ||
     320            clonedAlgorithm.ExecutionState == ExecutionState.Paused) {
     321          ticket.Wait();
     322          clonedAlgorithm.StartAsync(cancellationToken);
     323        }
     324      }
     325
     326      signal.Wait();
     327      if (pausePending) OnPaused();
     328      else OnStopped();
     329    }
     330
     331    public async Task StartAsync() { await StartAsync(CancellationToken.None); }
    277332    public async Task StartAsync(CancellationToken cancellationToken) {
    278       this.cancellationToken = cancellationToken;
    279       signaler.Reset();
    280       await Task.Run(() => {
    281         if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
    282           throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
    283 
    284         if (Algorithm != null) {
    285           //create cloned algorithms
    286           if (clonedAlgorithms.Count == 0) {
    287             int testSamplesCount = (SamplesEnd.Value - SamplesStart.Value) / Folds.Value;
    288 
    289             for (int i = 0; i < Folds.Value; i++) {
    290               IAlgorithm clonedAlgorithm = (IAlgorithm)algorithm.Clone();
    291               clonedAlgorithm.Name = algorithm.Name + " Fold " + i;
    292               IDataAnalysisProblem problem = clonedAlgorithm.Problem as IDataAnalysisProblem;
    293               ISymbolicDataAnalysisProblem symbolicProblem = problem as ISymbolicDataAnalysisProblem;
    294 
    295               int testStart = (i * testSamplesCount) + SamplesStart.Value;
    296               int testEnd = (i + 1) == Folds.Value ? SamplesEnd.Value : (i + 1) * testSamplesCount + SamplesStart.Value;
    297 
    298               problem.ProblemData.TrainingPartition.Start = SamplesStart.Value;
    299               problem.ProblemData.TrainingPartition.End = SamplesEnd.Value;
    300               problem.ProblemData.TestPartition.Start = testStart;
    301               problem.ProblemData.TestPartition.End = testEnd;
    302               DataAnalysisProblemData problemData = problem.ProblemData as DataAnalysisProblemData;
    303               if (problemData != null) {
    304                 problemData.TrainingPartitionParameter.Hidden = false;
    305                 problemData.TestPartitionParameter.Hidden = false;
    306               }
    307 
    308               if (symbolicProblem != null) {
    309                 symbolicProblem.FitnessCalculationPartition.Start = SamplesStart.Value;
    310                 symbolicProblem.FitnessCalculationPartition.End = SamplesEnd.Value;
    311               }
    312               clonedAlgorithm.Prepare();
    313               clonedAlgorithms.Add(clonedAlgorithm);
    314             }
    315           }
    316 
    317           //start prepared or paused cloned algorithms
    318           int startedAlgorithms = 0;
    319           foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
    320             if (startedAlgorithms < NumberOfWorkers.Value) {
    321               if (clonedAlgorithm.ExecutionState == ExecutionState.Prepared ||
    322                   clonedAlgorithm.ExecutionState == ExecutionState.Paused) {
    323 
    324                 // start and wait until the alg is started
    325                 using (var signal = new ManualResetEvent(false)) {
    326                   EventHandler signalSetter = (sender, args) => { signal.Set(); };
    327                   clonedAlgorithm.Started += signalSetter;
    328                   clonedAlgorithm.StartAsync(cancellationToken);
    329                   signal.WaitOne();
    330                   clonedAlgorithm.Started -= signalSetter;
    331 
    332                   startedAlgorithms++;
    333                 }
    334               }
    335             }
    336           }
    337           OnStarted();
    338         }
    339       }, cancellationToken);
     333      await Task.Factory.StartNew((ct) => Start((CancellationToken)ct), cancellationToken, cancellationToken);
    340334    }
    341335
     
    346340      if (!pausePending) {
    347341        pausePending = true;
    348         PauseAllClonedAlgorithms();
    349       }
    350     }
    351     private void PauseAllClonedAlgorithms() {
    352       foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
    353         if (clonedAlgorithm.ExecutionState == ExecutionState.Started)
    354           clonedAlgorithm.Pause();
     342        var toPause = clonedAlgorithms.Where(x => x.ExecutionState == ExecutionState.Started);
     343        if (toPause.Any()) {
     344          foreach (var optimizer in toPause) {
     345            // a race-condition may occur when the optimizer has changed the state by itself in the meantime
     346            try { optimizer.Pause(); } catch (InvalidOperationException) { }
     347          }
     348        }
     349        if (ExecutionState != ExecutionState.Paused) OnPaused();
    355350      }
    356351    }
     
    363358      if (!stopPending) {
    364359        stopPending = true;
    365         StopAllClonedAlgorithms();
    366       }
    367     }
    368     private void StopAllClonedAlgorithms() {
    369       foreach (IAlgorithm clonedAlgorithm in clonedAlgorithms) {
    370         if (clonedAlgorithm.ExecutionState == ExecutionState.Started ||
    371             clonedAlgorithm.ExecutionState == ExecutionState.Paused)
    372           clonedAlgorithm.Stop();
     360        var toStop = clonedAlgorithms.Where(x => x.ExecutionState == ExecutionState.Started || x.ExecutionState == ExecutionState.Paused);
     361        if (toStop.Any()) {
     362          foreach (var optimizer in toStop) {
     363            // a race-condition may occur when the optimizer has changed the state by itself in the meantime
     364            try { optimizer.Stop(); } catch (InvalidOperationException) { }
     365          }
     366        }
     367        if (ExecutionState != ExecutionState.Stopped) OnStopped();
    373368      }
    374369    }
     
    602597    private void Algorithm_ExecutionStateChanged(object sender, EventArgs e) {
    603598      switch (Algorithm.ExecutionState) {
    604         case ExecutionState.Prepared: OnPrepared();
     599        case ExecutionState.Prepared:
     600          OnPrepared();
    605601          break;
    606602        case ExecutionState.Started: throw new InvalidOperationException("Algorithm template can not be started.");
    607603        case ExecutionState.Paused: throw new InvalidOperationException("Algorithm template can not be paused.");
    608         case ExecutionState.Stopped: OnStopped();
     604        case ExecutionState.Stopped:
     605          OnStopped();
    609606          break;
    610607      }
     
    674671    private void ClonedAlgorithm_Paused(object sender, EventArgs e) {
    675672      lock (locker) {
    676         if (pausePending && clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Started))
    677           OnPaused();
     673        if (ExecutionState != ExecutionState.Paused) {
     674          if (clonedAlgorithms.All(alg => alg.ExecutionState != ExecutionState.Started)) {
     675            pausePending = true;
     676            signal.Set();
     677            ticket.Release();
     678          }
     679        }
    678680      }
    679681    }
     
    681683    private void ClonedAlgorithm_Stopped(object sender, EventArgs e) {
    682684      lock (locker) {
    683         if (!stopPending && ExecutionState == ExecutionState.Started) {
    684           IAlgorithm preparedAlgorithm = clonedAlgorithms.FirstOrDefault(alg => alg.ExecutionState == ExecutionState.Prepared ||
    685                                                                                 alg.ExecutionState == ExecutionState.Paused);
    686           if (preparedAlgorithm != null) preparedAlgorithm.StartAsync(cancellationToken);
    687         }
    688685        if (ExecutionState != ExecutionState.Stopped) {
    689           if (clonedAlgorithms.All(alg => alg.ExecutionState == ExecutionState.Stopped))
    690             OnStopped();
    691           else if (stopPending &&
    692                    clonedAlgorithms.All(
    693                      alg => alg.ExecutionState == ExecutionState.Prepared || alg.ExecutionState == ExecutionState.Stopped))
    694             OnStopped();
     686          if (clonedAlgorithms.All(alg => alg.ExecutionState == ExecutionState.Stopped || stopPending && alg.ExecutionState == ExecutionState.Prepared)) {
     687            stopPending = true;
     688            signal.Set();
     689          }
     690          ticket.Release();
    695691        }
    696692      }
     
    727723      pausePending = false;
    728724      ExecutionState = ExecutionState.Paused;
    729       signaler.Set();
    730725      EventHandler handler = Paused;
    731726      if (handler != null) handler(this, EventArgs.Empty);
     
    740735      runs.Add(new Run(string.Format("{0} Run {1}", Name, runsCounter), this));
    741736      ExecutionState = ExecutionState.Stopped;
    742       signaler.Set();
    743737      EventHandler handler = Stopped;
    744738      if (handler != null) handler(this, EventArgs.Empty);
  • branches/Async/HeuristicLab.Algorithms.DataAnalysis/3.4/FixedDataAnalysisAlgorithm.cs

    r13349 r15065  
    2222using System;
    2323using System.Threading;
    24 using System.Threading.Tasks;
    2524using HeuristicLab.Common;
    2625using HeuristicLab.Optimization;
     
    7069    }
    7170
    72     public override async Task StartAsync(CancellationToken cancellationToken) {
    73       await base.StartAsync(cancellationToken);
    74       var cancellationTokenSource = new CancellationTokenSource();
     71    public override void Start(CancellationToken cancellationToken) {
     72      base.Start(cancellationToken);
     73      OnStarted();
    7574
    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         });
     75      try {
     76        Run(cancellationToken);
     77      } catch (OperationCanceledException) {
     78      } catch (AggregateException ae) {
     79        if (ae.InnerExceptions.Count == 1) OnExceptionOccurred(ae.InnerExceptions[0]);
     80        else OnExceptionOccurred(ae);
     81      } catch (Exception e) {
     82        OnExceptionOccurred(e);
    9683      }
     84
     85      OnStopped();
    9786    }
    9887    private void Run(object state) {
  • branches/Async/HeuristicLab.Clients.OKB/3.3/RunCreation/EmptyAlgorithm.cs

    r13349 r15065  
    2121
    2222using System;
    23 using System.Threading;
    24 using System.Threading.Tasks;
    2523using HeuristicLab.Common;
    2624using HeuristicLab.Core;
     
    8280      throw new InvalidOperationException(string.IsNullOrEmpty(exceptionMessage) ? "Cannot prepare an EmptyAlgorithm." : exceptionMessage);
    8381    }
    84     public override async Task StartAsync(CancellationToken cancellationToken) {
     82    public override void Start() {
    8583      throw new InvalidOperationException(string.IsNullOrEmpty(exceptionMessage) ? "Cannot start an EmptyAlgorithm." : exceptionMessage);
    8684    }
  • branches/Async/HeuristicLab.Clients.OKB/3.3/RunCreation/OKBAlgorithm.cs

    r13354 r15065  
    252252    }
    253253    public void Start() {
    254       StartAsync().Wait();
    255     }
    256     public async Task StartAsync() {
    257       await StartAsync(CancellationToken.None);
    258     }
    259     public async Task StartAsync(CancellationToken cancellationToken) {
     254      Start(CancellationToken.None);
     255    }
     256    public void Start(CancellationToken cancellationToken) {
    260257      CheckUserPermissions();
    261258      if (!ClientInformation.Instance.ClientExists && storeRunsAutomatically) {
    262259        throw new MissingClientRegistrationException();
    263260      }
    264       await Algorithm.StartAsync(cancellationToken);
     261      Algorithm.Start(cancellationToken);
     262    }
     263    public async Task StartAsync() { await StartAsync(CancellationToken.None); }
     264    public async Task StartAsync(CancellationToken cancellationToken) {
     265      await Task.Factory.StartNew((ct) => Start((CancellationToken)ct), cancellationToken, cancellationToken);
    265266    }
    266267    public void Pause() {
  • branches/Async/HeuristicLab.Core/3.3/Engine.cs

    r13349 r15065  
    2323using System.Collections.Generic;
    2424using System.Threading;
    25 using System.Threading.Tasks;
    2625using HeuristicLab.Common;
    2726using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     
    8281    }
    8382
    84     public override async Task StartAsync(CancellationToken cancellationToken) {
    85       await base.StartAsync(cancellationToken);
    86       cancellationTokenSource = new CancellationTokenSource();
     83    public override void Start(CancellationToken cancellationToken) {
     84      base.Start(cancellationToken);
     85      cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
    8786      stopPending = false;
    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 => {
    91           try {
    92             t.Wait();
    93           }
    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             }
    102           }
    103           cancellationTokenSource.Dispose();
    104           cancellationTokenSource = null;
    105           if (stopPending) executionStack.Clear();
    106           if (executionStack.Count == 0) OnStopped();
    107           else OnPaused();
    108         });
     87
     88      try {
     89        Run((object)cancellationTokenSource.Token);
     90      } catch (OperationCanceledException) {
     91      } catch (AggregateException ae) {
     92        if (ae.InnerExceptions.Count == 1) OnExceptionOccurred(ae.InnerExceptions[0]);
     93        else OnExceptionOccurred(ae);
     94      } catch (Exception e) {
     95        OnExceptionOccurred(e);
    10996      }
     97
     98      cancellationTokenSource.Dispose();
     99      cancellationTokenSource = null;
     100      if (stopPending) executionStack.Clear();
     101      if (executionStack.Count == 0) OnStopped();
     102      else OnPaused();
    110103    }
    111104    protected override void OnStarted() {
     
    154147      try {
    155148        Run(cancellationToken);
    156       }
    157       finally {
     149      } finally {
    158150        timer.Elapsed -= new System.Timers.ElapsedEventHandler(timer_Elapsed);
    159151        timer.Stop();
  • branches/Async/HeuristicLab.Core/3.3/Executable.cs

    r13354 r15065  
    8484      ExecutionTime = TimeSpan.Zero;
    8585    }
    86     public void Start() {
    87       StartAsync().Wait();
     86    public virtual void Start() {
     87      Start(CancellationToken.None);
    8888    }
    89     public async Task StartAsync() {
    90       await StartAsync(CancellationToken.None);
    91     }
    92     public virtual async Task StartAsync(CancellationToken cancellationToken) {
     89    public virtual void Start(CancellationToken cancellationToken) {
    9390      if ((ExecutionState != ExecutionState.Prepared) && (ExecutionState != ExecutionState.Paused))
    9491        throw new InvalidOperationException(string.Format("Start not allowed in execution state \"{0}\".", ExecutionState));
     92    }
     93    public virtual async Task StartAsync() { await StartAsync(CancellationToken.None); }
     94    public virtual async Task StartAsync(CancellationToken cancellationToken) {
     95      await Task.Factory.StartNew((ct) => Start((CancellationToken)ct), cancellationToken, cancellationToken);
    9596    }
    9697    public virtual void Pause() {
  • branches/Async/HeuristicLab.Core/3.3/Interfaces/IExecutable.cs

    r13349 r15065  
    3232    void Prepare();
    3333    void Start();
     34    void Start(CancellationToken cancellationToken);
    3435    Task StartAsync();
    3536    Task StartAsync(CancellationToken cancellationToken);
  • branches/Async/HeuristicLab.DebugEngine/3.3/DebugEngine.cs

    r13349 r15065  
    2323using System.Linq;
    2424using System.Threading;
    25 using System.Threading.Tasks;
    2625using HeuristicLab.Common;
    2726using HeuristicLab.Core;
     
    161160        while (skipStackOperations && !(CurrentOperation is IAtomicOperation) && CanContinue)
    162161          ProcessNextOperation(true, cancellationTokenSource.Token);
    163       }
    164       catch (Exception ex) {
     162      } catch (Exception ex) {
    165163        OnExceptionOccurred(ex);
    166164      }
     
    174172    }
    175173
    176     public override async Task StartAsync(CancellationToken cancellationToken) {
    177       await base.StartAsync(cancellationToken);
    178       cancellationTokenSource = new CancellationTokenSource();
     174    public override void Start(CancellationToken cancellationToken) {
     175      base.Start(cancellationToken);
     176      cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
    179177      stopPending = false;
    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 => {
    183           try {
    184             t.Wait();
    185           }
    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             }
    194           }
    195           cancellationTokenSource.Dispose();
    196           cancellationTokenSource = null;
    197 
    198           if (stopPending) ExecutionStack.Clear();
    199           if (stopPending || !CanContinue) OnStopped();
    200           else OnPaused();
    201         });
    202       }
    203     }
    204 
     178
     179      try {
     180        Run(cancellationTokenSource.Token);
     181      } catch (OperationCanceledException) {
     182      } catch (AggregateException ae) {
     183        if (ae.InnerExceptions.Count == 1) OnExceptionOccurred(ae.InnerExceptions[0]);
     184        else OnExceptionOccurred(ae);
     185      } catch (Exception e) {
     186        OnExceptionOccurred(e);
     187      }
     188
     189      cancellationTokenSource.Dispose();
     190      cancellationTokenSource = null;
     191      if (stopPending) ExecutionStack.Clear();
     192      if (stopPending || !CanContinue) OnStopped();
     193      else OnPaused();
     194    }
    205195    protected override void OnStarted() {
    206196      Log.LogMessage("Engine started");
     
    252242          ProcessNextOperation(false, cancellationToken);
    253243        cancellationToken.ThrowIfCancellationRequested();
    254       }
    255       finally {
     244      } finally {
    256245        timer.Stop();
    257246        ExecutionTime += DateTime.UtcNow - lastUpdateTime;
     
    319308          }
    320309          CurrentOperation = null;
    321         }
    322         catch (Exception ex) {
     310        } catch (Exception ex) {
    323311          if (ex is OperationCanceledException) throw ex;
    324312          else throw new OperatorExecutionException(operation.Operator, ex);
  • 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    }
  • branches/Async/HeuristicLab.Problems.QuadraticAssignment.Algorithms/3.3/RobustTabooSearch.cs

    r13349 r15065  
    2323using System.Linq;
    2424using System.Threading;
    25 using System.Threading.Tasks;
    2625using HeuristicLab.Analysis;
    2726using HeuristicLab.Common;
     
    340339    }
    341340
    342     public override async Task StartAsync(CancellationToken cancellationToken) {
     341    public override void Start(CancellationToken cancellationToken) {
    343342      if (ExecutionState == ExecutionState.Prepared) {
    344343        int dim = Problem.Weights.Rows;
     
    352351        GlobalScope.Variables.Add(new Variable("MoveQualityMatrix", new DoubleMatrix(dim, dim)));
    353352      }
    354       await base.StartAsync(cancellationToken);
     353      base.Start(cancellationToken);
    355354    }
    356355
  • branches/Async/HeuristicLab.Tests/HeuristicLab-3.3/CollectObjectGraphTest.cs

    r12012 r15065  
    2424using System.Diagnostics;
    2525using System.Linq;
    26 using System.Threading;
    2726using System.Threading.Tasks;
    2827using HeuristicLab.Algorithms.GeneticAlgorithm;
     
    112111        algs.Add(ga);
    113112
    114         var cancellationTokenSource = new CancellationTokenSource();
    115         ga.StartSync(cancellationTokenSource.Token);
     113        ga.Start();
    116114        sw.Stop();
    117115        TestContext.WriteLine("{0}: {1} ", i, sw.Elapsed);
     
    144142          var sw = new Stopwatch();
    145143          sw.Start();
    146           ga.StartSync(new CancellationToken());
     144          ga.Start();
    147145          sw.Stop();
    148146          Console.WriteLine("{0}; Objects after execution: {1}", ga.Name, ga.GetObjectGraphObjects().Count());
  • branches/Async/HeuristicLab.Tests/HeuristicLab-3.3/GeneticAlgorithmTest.cs

    r12012 r15065  
    2121
    2222using System;
    23 using System.Threading;
    2423using HeuristicLab.Algorithms.GeneticAlgorithm;
    2524using HeuristicLab.Common;
     
    3938    }
    4039
    41     private EventWaitHandle trigger = new AutoResetEvent(false);
    4240    private Exception ex;
    4341
     
    4947      GeneticAlgorithm ga = (GeneticAlgorithm)XmlParser.Deserialize(@"Test Resources\GA_TSP.hl");
    5048      ga.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(ga_ExceptionOccurred);
    51       ga.Stopped += new EventHandler(ga_Stopped);
    5249      ga.SetSeedRandomly.Value = false;
    5350      ga.Seed.Value = 0;
     
    5552      ga.Prepare();
    5653      ga.Start();
    57       trigger.WaitOne();
    5854      if (ex != null) throw ex;
    5955
     
    8076      ex = e.Value;
    8177    }
    82 
    83     private void ga_Stopped(object sender, EventArgs e) {
    84       trigger.Set();
    85     }
    8678  }
    8779}
  • branches/Async/HeuristicLab.Tests/HeuristicLab.Algorithms.DataAnalysis-3.4/GaussianProcessRegressionTest.cs

    r12012 r15065  
    2222using System;
    2323using System.Linq;
    24 using System.Threading;
    2524using HeuristicLab.Common;
    2625using HeuristicLab.Problems.DataAnalysis;
     
    3938    }
    4039
    41     private EventWaitHandle trigger = new AutoResetEvent(false);
    4240    private Exception ex;
    4341
     
    6563
    6664      alg.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(cv_ExceptionOccurred);
    67       alg.Stopped += new EventHandler(cv_Stopped);
    6865
    6966      alg.Prepare();
    7067      alg.Start();
    71       trigger.WaitOne();
    7268      if (ex != null) throw ex;
    7369
     
    7874      ex = e.Value;
    7975    }
    80 
    81     private void cv_Stopped(object sender, EventArgs e) {
    82       trigger.Set();
    83     }
    8476  }
    8577}
  • branches/Async/HeuristicLab.Tests/HeuristicLab.Algorithms.DataAnalysis-3.4/GradientBoostingTest.cs

    r13157 r15065  
    11using System;
    22using System.Linq;
    3 using System.Threading;
    43using HeuristicLab.Data;
    5 using HeuristicLab.Optimization;
    64using HeuristicLab.Problems.DataAnalysis;
    75using Microsoft.VisualStudio.TestTools.UnitTesting;
     
    182180      #endregion
    183181
    184       RunAlgorithm(gbt);
     182      gbt.Start();
    185183
    186184      Console.WriteLine(gbt.ExecutionTime);
     
    210208      #endregion
    211209
    212       RunAlgorithm(gbt);
     210      gbt.Start();
    213211
    214212      Console.WriteLine(gbt.ExecutionTime);
     
    238236      #endregion
    239237
    240       RunAlgorithm(gbt);
     238      gbt.Start();
    241239
    242240      Console.WriteLine(gbt.ExecutionTime);
    243241      Assert.AreEqual(0.061954221604374943, ((DoubleValue)gbt.Results["Loss (train)"].Value).Value, 1E-6);
    244242      Assert.AreEqual(0.06316303473499961, ((DoubleValue)gbt.Results["Loss (test)"].Value).Value, 1E-6);
    245     }
    246 
    247     // same as in SamplesUtil
    248     private void RunAlgorithm(IAlgorithm a) {
    249       var trigger = new EventWaitHandle(false, EventResetMode.ManualReset);
    250       Exception ex = null;
    251       a.Stopped += (src, e) => { trigger.Set(); };
    252       a.ExceptionOccurred += (src, e) => { ex = e.Value; trigger.Set(); };
    253       a.Prepare();
    254       a.Start();
    255       trigger.WaitOne();
    256 
    257       Assert.AreEqual(ex, null);
    258243    }
    259244
  • branches/Async/HeuristicLab.Tests/HeuristicLab.Algorithms.DataAnalysis-3.4/SupportVectorMachineTest.cs

    r12012 r15065  
    2323using System.Collections.Generic;
    2424using System.Linq;
    25 using System.Threading;
    2625using HeuristicLab.Algorithms.DataAnalysis;
    2726using HeuristicLab.Common;
     
    5049    }
    5150
    52     private EventWaitHandle trigger = new AutoResetEvent(false);
    5351    private Exception ex;
    5452
     
    7169
    7270      cv.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(cv_ExceptionOccurred);
    73       cv.Stopped += new EventHandler(cv_Stopped);
    7471
    7572      cv.Prepare();
    7673      cv.Start();
    77       trigger.WaitOne();
    7874      if (ex != null) throw ex;
    7975
     
    10298      ex = e.Value;
    10399    }
    104 
    105     private void cv_Stopped(object sender, EventArgs e) {
    106       trigger.Set();
    107     }
    108100  }
    109101}
  • branches/Async/HeuristicLab.Tests/HeuristicLab.Scripting-3.3/Script Sources/GUIAutomationScriptSource.cs

    r11789 r15065  
    1 using System;
    2 using System.Linq;
    3 using System.Threading;
     1using System.Linq;
    42using System.Windows.Forms;
    53
    64using HeuristicLab.Algorithms.GeneticAlgorithm;
    7 using HeuristicLab.Core;
    85using HeuristicLab.MainForm;
    96using HeuristicLab.MainForm.WindowsForms;
     
    1310
    1411public class GUIAutomationScript : HeuristicLab.Scripting.CSharpScriptBase {
    15   readonly ManualResetEvent mutex = new ManualResetEvent(false);
    16 
    1712  public override void Main() {
    1813    var ga = new GeneticAlgorithm {
     
    2722      ga.PopulationSize.Value *= 2;
    2823    }
    29 
    30     experiment.ExecutionStateChanged += OnExecutionStateChanged;
    3124    experiment.Start();
    32     mutex.WaitOne();
    3325
    3426    vars.experiment = experiment;
     
    3931    bubbleChart.Controls.OfType<ComboBox>().Single(x => x.Name == "xAxisComboBox").SelectedItem = "PopulationSize";
    4032  }
    41 
    42   private void OnExecutionStateChanged(object sender, EventArgs e) {
    43     if (((IExecutable)sender).ExecutionState == ExecutionState.Stopped)
    44       mutex.Set();
    45   }
    4633}
  • branches/Async/HeuristicLab.Tests/HeuristicLab.Tests.csproj

    r13266 r15065  
    428428  <ItemGroup>
    429429    <Compile Include="AssemblyInitializer.cs" />
    430     <Compile Include="HeuristicLab-3.3\AlgorithmExtensions.cs" />
    431430    <Compile Include="HeuristicLab-3.3\CloningConstructorTest.cs" />
    432431    <Compile Include="HeuristicLab-3.3\CollectObjectGraphTest.cs" />
Note: See TracChangeset for help on using the changeset viewer.